如何分离嵌套的JSON

2024-04-25 22:50:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个JSON数据结构如下:

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

这里的键a总是唯一的,即使是嵌套的。你知道吗

我想分离JSON数据,使其看起来像这样:

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

JSON数据可以嵌套多次。 怎么做?你知道吗


Tags: 数据json数据结构
2条回答

不确定Python实现,但在JavaScript中,这可以使用递归实现:

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

只有当对象键名而不是数字时,这才会按预期工作。你知道吗

JSFiddle。你知道吗

我会使用一个输入和输出堆栈:

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可以是dict的原因。然后更换

output_stack.append(front)

output_dict[front['a']] = front

相关问题 更多 >