1

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.

1
  • I don't see any attempt in your code to go deep into the structure. Commented Dec 4, 2017 at 17:21

1 Answer 1

2
 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.

Sign up to request clarification or add additional context in comments.

1 Comment

Oh. My. God. Your answer is so simple. THANK YOU!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.