如何从json创建嵌套的json并用单个键替换不同的键值

时间:2019-06-15 10:07:23

标签: python json pandas dataframe

我有一个像这样的json(这是通过将熊猫数据帧转换为json形成的):

"columns0": {
    "0": 9100,
    "4": 8550,
    "9": 0,
    "11": 1.5,
    "12": 35000,
    "13": 0
},
"columns1": {
    "0": 5000,
    "4": 38317.7,
    "9": 423,
    "11": 19.14,
    "12": 35000,
    "13": 320
}

我想修改此json,这将是一个嵌套json,其中每个嵌套json的键都是唯一的。输出json应该看起来像这样:

"columns0": {
    {"key1": 9100},
    {"key1": 8550},
    {"key1": 0},
    {"key1": 1.5},
    {"key1": 35000},
    {"key1": 0}
},
"columns1": {
    {"key1": 5000},
    {"key1": 38317.7},
    {"key1": 423},
    {"key1": 19.14},
    {"key1": 35000},
    {"key1": 320}
}

如何使用python做到这一点?

3 个答案:

答案 0 :(得分:0)

  

正如您在新json的预期输出中提到的那样,Python不允许创建没有键和值对的字典。

jsonData = { "columns0": {
            "0": 9100,
            "4": 8550,
            "9": 0,
            "11": 1.5,
            "12": 35000,
            "13": 0
        },
        "columns1": {
            "0": 5000,
            "4": 38317.7,
            "9": 423,
            "11": 19.14,
            "12": 35000,
            "13": 320
        }
    }

new_json = {}
for key in jsonData:
    sub_list = []
    for neste_key in jsonData[key]:
        sub_json = dict(key1=jsonData[key][neste_key])
        sub_list.append(sub_json)

    if len(sub_list) > 0:
        new_json[key] = sub_list

print(new_json)

O / P:

{
  'columns0': [
    {'key1': 9100},
    {'key1': 8550},
    {'key1': 0},
    {'key1': 1.5},
    {'key1': 35000},
    {'key1': 0}
  ],
  'columns1': [
    {'key1': 5000},
    {'key1': 38317.7},
    {'key1': 423},
    {'key1': 19.14},
    {'key1': 35000},
    {'key1': 320}
  ]
}

答案 1 :(得分:0)

您的预期输出不是有效的json也不是dict。

"columns0": {
    {"key1": 9100},
    {"key1": 8550},
    {"key1": 0},
    {"key1": 1.5},
    {"key1": 35000},
    {"key1": 0}
}

也许你是说一个对象数组?

"columns0": [
    {"key1": 9100},
    {"key1": 8550},
    {"key1": 0},
    {"key1": 1.5},
    {"key1": 35000},
    {"key1": 0}
]

如果是这样,此代码应该可以工作:

old_dict = {
    "columns0": {
        "0": 9100,
        "4": 8550,
        "9": 0,
        "11": 1.5,
        "12": 35000,
        "13": 0
    },
    "columns1": {
        "0": 5000,
        "4": 38317.7,
        "9": 423,
        "11": 19.14,
        "12": 35000,
        "13": 320
    }
}

new_dict = {}

for c_name, c_values in old_dict.items():
    new_dict[c_name] = [{"key1": v } for v in c_values.values()]

答案 2 :(得分:0)

我想这就是您想要的。

    new_json={}
    for i in range(0,2):
        s="columns"+str(i)
        l = []
        for v in j[s].values():
            t={}
            t["key1"]=v
            l.append(t)
        new_json[s]=l

new_json看起来像这样:

   {'columns0': 
    [{'key1': 9100}, 
    {'key1': 8550}, 
    {'key1': 0}, 
    {'key1': 1.5}, 
    {'key1': 35000}, 
    {'key1': 0}], 
    'columns1': 
    [{'key1': 5000}, 
    {'key1': 38317.7}, 
    {'key1': 423}, 
    {'key1': 19.14}, 
    {'key1': 35000}, 
    {'key1': 320}]
}