简体   繁体   English

转换 JSON 键和值

[英]Transforming JSON keys and values

I have a simple json in python that looks like :我在 python 中有一个简单的 json,看起来像:

{
    "list": [{
            "key1": "value1"
        },
        {
            "key1": "value1"
        }
    ]
}

I want to transform this to the following json.我想将其转换为以下 json。 Any suggestions how I can do it with python without installing additional libraries?任何建议如何在不安装其他库的情况下使用 python 来完成?

{
    "list": [{
        "keys": {
            "name": "key1",
            "value": "value1"
        }
    }, {
        "keys": {
            "name": "key1",
            "value": "value1"
        }
    }]
}

Not sure from your question if you already have the json read into a variable, or if it is in a file.从你的问题中不确定你是否已经将 json 读入了一个变量,或者它是否在一个文件中。 This is assuming you have it in a variable already:这是假设你已经在一个变量中了:

in_json = {
    "list": [{
            "key1": "value1"
        },
        {
            "key2": "value2"
        }
    ]
}

out_json = {"list":[]}
for kd in in_json["list"]:
    sub_kd = {"keys": {}}
    for k,v in kd.iteritems():
        sub_kd["keys"]["name"] = k
        sub_kd["keys"]["value"] = v

    out_json["list"].append(sub_kd)

print(out_json)

It just loops through the json making dictionaries to append to the out_json dictionary.它只是遍历 json 制作字典以附加到out_json字典。 You could make this print pretty with the json library and also save to file with it你可以用 json 库使这个打印漂亮,也可以用它保存到文件

You didn't indicate exactly what contains the JSON data is in, so I've put it all in a string in the example code below and uses the json.loads() function to turn it into a Python dictionary.您没有准确指出 JSON 数据的具体内容,因此我在下面的示例代码中将其全部放入一个字符串中,并使用json.loads()函数将其转换为 Python 字典。 If it's in a file, you can use the module's json.load() function instead.如果它在文件中,您可以改用模块的json.load()函数。

It also make the assume that each sub-JSON object in the "list" list consists of only one key/value pair as shown in your question.它还假设"list"列表中的每个子 JSON 对象仅包含一个键/值对,如您的问题所示。

The code below changes the deserialized dictionary in-place and pretty-prints the result of doing that by using the json.dumps() function to reserialize it.下面的代码就地更改反序列化的字典并通过使用json.dumps()函数重新序列化它来漂亮地打印结果。

Note that I changed the keys and values in sample input JSON slightly to make it easier to see the correspondence between it and the printed results.请注意,我稍微更改了示例输入 JSON 中的键和值,以便更容易查看它与打印结果之间的对应关系。

import json


json_in = '''
    {
        "list": [
            {
                "key1": "value1"
            },
            {
                "key2": "value2"
            }
        ]
    }
'''

json_data = json.loads(json_in)  # Deserialize.

for i, obj in enumerate(json_data['list']):
    # Assumes each object in list contains only one key, value pair.
    newobj = { 'name': next(iter(obj.keys())),
              'value': next(iter(obj.values()))}
    json_data['list'][i] = {'keys': newobj}

print(json.dumps(json_data, indent=4))  # Reserialize and print.

Printed result:打印结果:

{
    "list": [
        {
            "keys": {
                "name": "key1",
                "value": "value1"
            }
        },
        {
            "keys": {
                "name": "key2",
                "value": "value2"
            }
        }
    ]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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