2021年4月6日星期二

Add Key to top level of JSON file python

I did not know the proper way to title my question but here it goes. This is my current code; for sake of sensitive data, I have changed to fake URLs.

Site1 = 'testsite.com/data/api=028130u12'  Site2 = 'testsite.com/data/api=048843u78'  Site3 = 'testsite.com/data/api=930293u18'    URLs = [Site1,          Site2,          Site3]    json_list = []    for url in URLs:      response = requests.get(url)      data = response.json()      json_list.append(data)    with open('data.json', 'w+') as f:      json.dump(json_list, f, sort_keys=True, indent=4)  

When I run it I get a Json file similar to below. I have shortened it greatly because each value has nested k,v[k,v[k,v]] in them.

[    {        "emplPerf":       "emplID":       "emplList":       "emplHours":    },    {        "emplPerf":       "emplID":       "emplList":       "emplHours":    },    {        "emplPerf":       "emplID":       "emplList":       "emplHours":    }  ]  

My question is. How can I go about changing the data.json file or doing it when requesting the data so that at the beginning of each batch block the site that the data was grabbed from is added?

What I would like;

[    {       "Site1" : [{          "emplPerf":          "emplID":          "emplList":          "emplHours":    }]},    {       "Site2" : [{         "emplPerf":         "emplID":         "emplList":         "emplHours":    }]},    {        "Site3" : [{         "emplPerf":         "emplID":         "emplList":         "emplHours":    }]}  ]  

Please excuse any formatting errors. Hopefully what I am trying to do came across fairly well.

https://stackoverflow.com/questions/66979374/add-key-to-top-level-of-json-file-python April 07, 2021 at 11:57AM

没有评论:

发表评论