简体   繁体   中英

How to separate nested JSON

I have a JSON data with structure like this:

{ "a":"1",
  "b":[{ "a":"4",
         "b":[{}],
         "c":"6"}]
  "c":"3"
}

Here the key a is always unique even if nested.

I want to separate my JSON data so that it should look like this:

{"a":"1"
 "b":[]
 "c":"3"
},
{"a":"4",
 "b":[],
 "c":"6"
}

JSON data can be nested up to many times. How to do that?

I'd use an input and output stack:

x = {
    "a":1,
    "b":[
         {
             "a":2,
             "b":[ { "a":3, }, { "a":4, } ]
         }
    ]
}

input_stack = [x]
output_stack = []

while input_stack:
     # for the first element in the input stack
     front = input_stack.pop(0)
     b = front.get('b')
     # put all nested elements onto the input stack:
     if b:
         input_stack.extend(b)
     # then put the element onto the output stack:
     output_stack.append(front)

output_stack ==
[{'a': 1, 'b': [{'a': 2, 'b': [{'a': 3}, {'a': 4}]}]},
 {'a': 2, 'b': [{'a': 3}, {'a': 4}]},
 {'a': 3},
 {'a': 4}]

output_stack can be a dict of cause. Then replace

output_stack.append(front)

with

output_dict[front['a']] = front

Not sure about a Python implementation, but in JavaScript this could be done using recursion:

function flatten(objIn) {
  var out = [];
  function unwrap(obj) {
    var arrayItem = {};
    for(var idx in obj) {
      if(!obj.hasOwnProperty(idx)) {continue;}
      if(typeof obj[idx] === 'object') {
        if(isNaN(parseInt(idx)) === true) {
          arrayItem[idx] = [];
        }
        unwrap(obj[idx]);
        continue;
      }
      arrayItem[idx] = obj[idx];
    }
    if(JSON.stringify(arrayItem) !== '{}') {
      out.unshift(arrayItem);
    }
  }
  unwrap(objIn);

  return out;
}  

This will only work as expected if the object key names are not numbers.

See JSFiddle .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM