Home > Blockchain >  need to turn JSON values into keys
need to turn JSON values into keys

Time:06-16

I have some json that I would like to transform from this:

           [
            {
               "name":"field1",
               "intValue":"1"
            },
            {
               "name":"field2",
               "intValue":"2"
            },
            ...
            {
               "name":"fieldN",
               "intValue":"N"
            }
            ]

into this:

{ "field1" : "1",
  "field2" : "2",
  ...
  "fieldN" : "N",
}

For each pair, I need to change the value of the name field to a key, and the values of the intValue field to a value. This doesn't seem like flattening or denormalizing. Are there any tools that might do this out-of-the-box, or will this have to be brute-forced? What's the most pythonic way to accomplish this?

CodePudding user response:



parameters = [ # assuming this is loaded already
    {
        "name":"field1",
        "intValue":"1"
    },
    {
        "name":"field2",
        "intValue":"2"
    },
    {
        "name":"fieldN",
        "intValue":"N"
    }
]

 

field_int_map = dict()

for p in parameters:
    field_int_map[p['name']] = p['intValue']
    

yields {'field1': '1', 'field2': '2', 'fieldN': 'N'}

or as a dict comprehension

field_int_map = {p['name']:p['intValue'] for p in parameters}

This works to combine the name attribute with the intValue as key:value pairs, but the result is a dictionary instead of the original input type which was a list.

CodePudding user response:

Use dictionary comprehension:

json_dct = {"parameters":
            [
                {
                    "name":"field1",
                    "intValue":"1"
                },
                {
                    "name":"field2",
                    "intValue":"2"
                },
                {
                    "name":"fieldN",
                    "intValue":"N"
                }
            ]}

dct = {d["name"]: d["intValue"] for d in json_dct["parameters"]}
print(dct)
# {'field1': '1', 'field2': '2', 'fieldN': 'N'}
  • Related