Extract values from complex JSON

I have a large and complex JSON and I want to extract specific values to a csv file

I created the Javascript function to convert the JSON to CSV. I don’t know how to extract the values.

Answer

Here’s the solution. We import the json file, then search through the record for keys that include “answer_comments”, since all the questions have that key.

Then we take the name of title of the questions using regex.

Now that we have the title of the questions, we can loop through them and get the values for each.

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);