简体   繁体   中英

Transforming JSON keys and values

I have a simple json in python that looks like :

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

I want to transform this to the following json. Any suggestions how I can do it with python without installing additional libraries?

{
    "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. 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. You could make this print pretty with the json library and also save to file with it

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. If it's in a file, you can use the module's json.load() function instead.

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.

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.

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.

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"
            }
        }
    ]
}

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