user-44651
user-44651

Reputation: 4124

Create JSON object from complex string array

I have been given these test inputs that need to be parsed into a JSON object organized by their Key split by an underscore.

var testInput1 = '{"Data_Structure_Test1": "Test1 Data"}';
var testInput2 = '{"Data_Structure_Test2": "Test2 Data"}';
var testInput3 = '{"Data_Structure_Test3": "Test3 Data"}';
var testInput4 = '{"Data_AnotherStructure": "AnotherStructure Data"}';
var testInput5 = '{"Data_JustAnother": "JustAnother Data"}';
var testInput6 = '{"NewData_NewTest": "NewTest Data"}';

So the above testInputs should spit out:

{
    "Data": {
        "Structure": {
            "Test1": "Test1 Data",
            "Test2": "Test2 Data",
            "Test3": "Test3 Data"
        },
        "AnotherStructure": "AnotherStructure Data",
        "JustAnother": "JustAnother Data"
    },
    "NewData": {
        "NewTest": "NewTest Data"
    }
}

I can't seem to get the JSON objects to collect into the correct container.

Here is a JSFiddle that I have been using to test with

Here is my function that I am calling to parse the string

function parse_input(aInput) {

let jObj = JSON.parse(aInput);

  for (let key in jObj) {

    let objKeys = key.split("_");

    for (i = 0; i < objKeys.length; i++) {

      if (data.hasOwnProperty(objKeys[i])) {

        data[key] = jObj[key];
      } else {

        data[objKeys[i]] = jObj[key];
      }
    }

And how I am passing in the inputs:

var data = {};

parse_input(testInput1);
parse_input(testInput2);
parse_input(testInput3);
parse_input(testInput4);
parse_input(testInput5);
parse_input(testInput6);

var result = JSON.stringify(data, undefined, '\t');

Can anyone see what I am doing wrong?

I do have access the jQuery framework if that will make this any easier.

Upvotes: 1

Views: 67

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138417

 function parse_input(json){
   const obj = JSON.parse(json);
   for(const key in obj){
      const keys = key.split("_");
      keys.slice(0,-1).reduce(function(obj, key){
          return obj[key] || (obj[key] = {});
      }, data)[keys.pop()] = obj[key];
   }
}

You may want to use reduce to go deep into the data object.

Upvotes: 2

Related Questions