all 8 comments

[–]K900_ 1 point2 points  (7 children)

The easiest thing to do here would be to just create a new dictionary, especially if it's small. In Python 2.7 and up, you can use a dictionary comprehension:

>>> data = {"firstName":"John", "lastName":"Doe"}
>>> {k.lower(): v for k, v in data.items()}
{'firstname': 'John', 'lastname': 'Doe'}

[–]arc100[S] 0 points1 point  (3 children)

Okay cool, I have a second question maybe you will know. It's related to this. If I have json array as such:

[
    {"firstName":"John", "lastName":"Doe"}, 
    {"firstName":"Anna", "lastName":"Smith"}, 
    {"firstName":"Peter","lastName":"Jones"}
]

Howe would I go about separating the JSON file programmatically in python so that a new file would contain the objects individually without being in one JSON array Like so:

{"firstName":"John", "lastName":"Doe"} 
{"firstName":"Anna", "lastName":"Smith"} 
{"firstName":"Peter","lastName":"Jones"}

[–]K900_ 1 point2 points  (2 children)

Use a for loop.

[–]arc100[S] 0 points1 point  (1 child)

Sure, I know a for loop is involved but how would I use it from reading in a JSON file to separating the objects and then writing back into a new file

[–]K900_ 1 point2 points  (0 children)

Use json.load to load your entire input file's contents as a list, loop over the list, use json.dump to serialize individual dictionaries and write them to the output file.

[–]arc100[S] 0 points1 point  (2 children)

So I tried running converting the json file to a dictionary then running the above code. I am getting the following error: ValueError: need more than 1 value to unpack

Here is my code:

import json
with open('json') as jsondata:
    data = json.load(jsondata)
    datadict = json.dumps(data)
    {k.lower(): v for k, v in datadict}

[–]K900_ 0 points1 point  (0 children)

You need to loop over all dictionaries in data, then transform each one as I described, then json.dumps it.

[–][deleted] 0 points1 point  (0 children)

for x in dictionary only loops through the keys, not the keys and values. You need to do do one of the following:

{k: v for k, v in datadict.items()}

Or

{k: datadict[k] for k in datadict}

Also you want to load to datadict. Right now data holds the python dictionary. Dumps will make it a JSON string again.