Search code examples
javascriptpythonjsondecodeencode

How do I parse json keys into json objects


So I'm having this issue where I'm trying to convert something such as

[0]['question']: "what is 2+2",
[0]['answers'][0]: "21",
[0]['answers'][1]: "312",
[0]['answers'][2]: "4"

into an actual formated json object like so

[
  {
    'question': 'what is 2+2',
    'answers': ["21", "312", "4"]
  }
]

but I'm not too sure what approach to take to make this work.

I'm planning on parsing the key-values in the first snipped through javascript and decode it into a json object like in the second snippet through python.

Have you got any idea on how to do this? I'd accept an example in pretty much any language as it shouldn't be much of a worry to read the concept behind them.


Solution

  • Something like this. You need to handle input errors.

    A function to take a data structure and add stuff to it based on input

    function add(old, input) {
      var index = input[0];
      var section = input[1];
      if (old[index] == undefined) {
        old[index] = {}
      };
      if (section == "question") {
        old[index]['question'] = input[2];
      }
    
      if (section == "answers") {
        var answerIndex = input[2];
        var answerValue = input[3];
    
        if (old[index]["answers"] == undefined) {
          old[index]["answers"] = []
        };
    
        old[index]["answers"][answerIndex] = answerValue
      }
    
      return old;
    }
    

    Some inputs:

    var inputs = [[0, "question", "what"],
                  [0, "answers", 0, "21"],
                  [0, "answers", 1, "22"]];
    
    var result = {};
    
    inputs.forEach(function(input) { add(result, input) })
    
    JSON.stringify(result)
    
    
    "{"0":{"question":"what","answers":["21","22"]}}"