Home > Software engineering >  Add JSON key names to json values in an array. File contains bulk JSONs
Add JSON key names to json values in an array. File contains bulk JSONs

Time:09-30

I have a file that contains list of jsons (more than 10k), something like this

{"name":"abc", "location": {"coordinates": [-94.350096,39.049484]}} 
{"name":"xyz", "location": {"coordinates": [-91.350096,36.049484]}} 
{"name":"lmn", "location": {"coordinates": [-84.350096,69.049484]}} 
{"name":"pqr", "location": {"coordinates": [-90.350096,31.049484]}}

I want to convert this to following

{"name":"abc", "location": {"coordinates": ["latitude":-94.350096,"longitude":39.049484]}} 
{"name":"xyz", "location": {"coordinates": ["latitude":-91.350096,"longitude":36.049484]}}
{"name":"lmn", "location": {"coordinates": ["latitude":-84.350096,"longitude":69.049484]}} 
{"name":"pqr", "location": {"coordinates": ["latitude":-90.350096,"longitude":31.049484]}}

Any reference to any such code?

CodePudding user response:

Read the file line by line and load it as dict using json module. Finally, edit it as required.

import json
with open("test.txt") as f:
    for line in f:
        data = json.loads(line)
        coords = data["location"]["coordinates"]
        data["location"]["coordinates"] = {"latitute": coords[0], "longitude": coords[1]}
        print(data)
  • Related