在Python中将Json文件嵌套的字典列表转换为字典行

时间:2019-06-25 22:35:35

标签: python json list nested

我有一个json文件,我需要将字典列表转换为多行字典。

示例代码:

(defun main ()
  (let ((x 0))
    (declare (special x))
    (fum)))

(defun fum ()
  (let ((x 1))  ;inadvertant? use of x
    (setf x 2))
  (foo))

(defun foo ()
  (declare (special x))
  (bar x))

(defun bar (arg)  ;final consumer of x
  arg)

(main) => 0

理想的输出:


{
"A": {
 "B": {
  "C": [
    {
    "1":"value_x",
    "2":"value_x",
    "3":"value_x"
   },
  {"1":"value_y",
   "2":"value_y",
    "3":"value_y"
   }
  ]}}}

我试图展平json,但是一行结果难以辨认

{"A_B_C_1":"value_x"},
{"A_B_C_2":"value_x"},
{"A_B_C_3":"value_x"},
{"A_B_C_1":"value_y"},
{"A_B_C_2":"value_y"},
{"A_B_C_3":"value_y"}

1 个答案:

答案 0 :(得分:0)

这是使用递归来获得所需输出的另一种尝试。请记住,以下代码是根据您提供的示例数据制作的:

"A1"
"A2toB B1"
"A2toB B2"
"A3"

输出将是:

import json

def flatten(data,outList,resultData):
    for key, value in data.items():
        if isinstance(value, dict):
            outList.append(key)
            flatten(value,outList,resultData)
        elif isinstance(value, list):
            outList.append(key)
            for elem in value:
                for inner_key, inner_value in elem.items():
                    outList.append(inner_key)
                    final_key = '_'.join(outList)
                    resultData.append({final_key : inner_value})
                    outList = outList[:-1]
    return resultData

def showData(resultData):
    for elem in resultData:
        print(elem)

with open('data.json') as inFile:
    data = json.loads(inFile.read())
    resultData = flatten(data,[],[])
    showData(resultData)