Uncover data from intricate JSON structures

I'm facing a challenge with a large JSON file that contains complex data. My goal is to extract specific values from this JSON and convert them into a CSV file using a JavaScript function that I have created. However, I am unsure about the process of extracting these values.

Answer №1

Here is our approach: We start by importing a json file and then proceed to look for keys that contain "answer_comments" in the record, as this key is present in all the questions.

Next, we use regex to extract the titles of the questions.

Once we have the question titles, we iterate through them to retrieve the corresponding values.

const data = require("./data.json");
const record = data["ex:recordCollection"]["ex:record"];

const questions = Object.keys(record).filter((a) =>
  a.toLowerCase().includes("answer_comments")
);

const result = questions.map((q) => {
  const title: string = q.match(/(?<=ex:)(.*)(?=__)/gm)[0];

  return {
    question: title,
    answer: record[`ex:${title}`]["ex:Item"]["_text"],
    answer_comment: !record[`ex:${title}__Answer_Comments`] && "",
    implementation: record[`ex:${title}__Implementation`]
      ? record[`ex:${title}__Implementation`]["ex:Item"]["_text"]
      : "",
    implementation_comments:
      !record[`ex:${title}__Implementation_Comments`] && "",
  };
});

console.log(result);

Answer №3

JSON.parse is the go-to function for parsing JSON data and converting it into a native JavaScript object. To use it, you can fetch the file and pass it to this function.

For example:

const fs = require("fs");
var json = JSON.parse(fs.readFileSync('/path/to/file.json', 'utf8'));

You can also directly require a JSON file like so:

const json = require("path/to/file.json");

However, I advise against this method due to its drawbacks:

  1. require is blocking, meaning that loading large JSON files will halt execution until it's finished.
  2. The file is only read once, and subsequent calls will return cached versions instead.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Vue.js 2.x to Encode HTML Entities When Binding to v-bind:href

In my Vue application, I am using a v-for loop v-for="item in resultQuery" and outputting a link within this loop: <a v-bind:href="item.url"> <h2 class="title" v-html="item.title" v-bind:title="item.title"></h2> </a> In some cases, ...

Tips for extracting JSON components from an HTTP response string using Python

I am currently learning how to parse JSON data from an HTTP API in Python. Below is the code I have written to parse the HTTP content as a string and extract a JSON object array: import json from urllib.request import urlopen apilink = urlopen("api link" ...

Reduce and combine JavaScript files without the need for Grunt or Gulp

My project involves working with over 50 JavaScript files that I want to combine and compress to optimize file size and minimize HTTP requests. The catch is, the client's system does not have Node or npm installed. How can I accomplish this task witho ...

assign a CSS style based on a JavaScript variable

I am looking to dynamically set the height of a cell in a table based on the window's height. I plan to retrieve the window's height using JavaScript and then incorporate it into the div style. <script language="javascript"> var width = is ...

Exploring JavaScript functions within the Rails 4 asset pipeline directory

I am facing an issue while trying to use a JavaScript function through the Chrome Console after embedding that function within the Rails Asset Pipeline Manifest. To achieve this, I followed these steps to create and set up a basic Rails 4.2.4 App: $ rails ...

The request has encountered a 400 bad request error when using

I am encountering an issue with my web application. The frontend is built using React, the backend uses NodeJS, and the database is MongoDB. I have successfully implemented a registration form that posts data to the Node JS server via Axios and interacts ...

What is the best way to choose the element directly beneath a specific element using jQuery?

I am facing a challenge where I need to manipulate HTML content using only jQuery, without changing the original structure. The requirement is to display and slide down content with a specific class (current) upon clicking on an h1 tag. However, I am strug ...

Removing event notifications with Google Calendar API v3 (JavaScript): A Step-by-Step Guide

After creating a JSON object with event details, I attempted to add it to Google Calendar using the provided code snippet: function addEvent() { gapi.client.load('calendar', 'v3', function() { var request = gapi.client.calendar.e ...

Is there a way to assign a jQuery onclick function to only select table columns or a particular class within an editable table?

I would like to enable editing for specific columns named Home_Score and Away_Score in my table //edit.js file $(function() { //when a td element within tbody is clicked $('tbody').on('click','td',function() { ...

Steps for updating lodash to the newest version

While using npm on the Debian Linux distribution to install Jpm, I encountered errors related to the versions of lodash installed, as shown below: test@localhost:~# npm install jpm --global npm WARN deprecated <a href="/cdn-cgi/l/email-protection" clas ...

The expect.objectContaining() function in Jest does not work properly when used in expect.toHaveBeenCalled()

Currently, I am working on writing a test to validate code that interacts with AWS DynamoDB using aws-sdk. Despite following a similar scenario outlined in the official documentation (https://jestjs.io/docs/en/expect#expectobjectcontainingobject), my asser ...

Determine the total number of selected items in MagicSuggest when it loses focus

I have been working with MagicSuggest and I am currently facing an issue where I need to retrieve the length of selections on a blur event. Interestingly, my code functions perfectly fine when a new selection is added using the ENTER key, but it fails when ...

Making a Connection with Ajax in Django: Adding Friends

I have been exploring the capabilities of Django-Friends My goal is to make it so that when a user clicks on the add friend button, it either disappears or changes to say "Request sent". However, I am encountering an issue where the button does not disapp ...

Exploring the Functions of JavaScript with Google's Cloud Storage

I have been attempting to upload images into buckets on Google Cloud Storage using the JSON API and the Javascript sample provided in the documentation. Although I am able to successfully upload pictures, I am encountering an issue where it prompts me to ...

Combining Multiple 3D JSON Objects in JavaScript [or jQuery]

Looking to combine multiple JSON objects into one? I have a code snippet that you can use! Here is the code: http://jsfiddle.net/5Uz27/ The issue with this code is that it only merges objects on the first level, causing deeper levels to be overwritten. T ...

Establish a connection between two pre-existing tables by utilizing the Sequelize framework

I have two tables already set up (User and PaymentPlan), but they were not initially linked together. PaymentPlan.ts import { DataTypes, Model } from "sequelize"; import { sequelize } from "./DBConnections/SequelizeNewConnection"; exp ...

Issues with vue-moment.js in Vue

I'm struggling with incorporating vue-moment or moment.js into a .vue file to work with dates. I want to be able to manipulate a date in the Vue method to calculate the timespan between a past and current time, updating it dynamically. After searching ...

Sorting arrays in JavaScript can become tricky when dealing with arrays that contain values from two different arrays

When working with two arrays in JavaScript that are received from PHP, I combine them into a single array. Each element in these arrays contains a created_at value (from Laravel), and I want to sort these elements by their created_at values. The issue ari ...

PHP submission fails to transmit latest information to MySQL database

Where should I begin? I have developed a UK CAD system for a UK Police roleplay clan. The specific area in question can be viewed here. Initially, everything was working fine. I created an Intel page and added a new column to the MySQL table. However, wh ...

Having trouble with npm debounce in ReactJS?

When using the npm debounce package in ReactJS, I encountered an error with the code below: Javascript - Uncaught TypeError: Object(...) is not a function The error occurs when passing the function into the debounce() method. import React, { Component ...