I'm connecting to a REST service and I get a response in that format
{
"Outputs": {
"Actual": [
"2017-08-29T14:37:47.137",
"2017-08-30T13:07:09.563",
"2017-08-30T14:41:29.023"
],
"Start": [
"2017-08-29T14:36:12.42",
"2017-08-30T12:59:53.05",
"2017-08-30T14:40:45.34"
],
"NumScrapsList": [
0,
3,
...
but I would like to have it in that form
{
"Outputs":[
{
"NumScrapsList":0,
"Actual":"2017-08-29T14:37:47.137",
"Start":"08-29T14:36:12.42"
},
{
"NumScrapsList":3,
"Actual":"2017-08-30T13:07:09.563",
"Start":"2017-08-30T12:59:53.05"
}
]
}
I'm quite new of Python code and JSON format and I cannot know I don't know where to start to "remap" the result. Could you put me in the right direction?
Here is my little piece of code:
with requests.post(url, headers=headers, data=data, stream=True) as r:
r.raise_for_status()
with open('outfile.json', 'wb') as f_out:
for chunk in r.iter_content(chunk_size=8192):
f_out.write(chunk)
Thank you
CodePudding user response:
Here is a generic approach that should work for your use case:
from pprint import pprint
resp = {
"Outputs": {
"Actual": [
"2017-08-29T14:37:47.137",
"2017-08-30T13:07:09.563",
"2017-08-30T14:41:29.023"
],
"Start": [
"2017-08-29T14:36:12.42",
"2017-08-30T12:59:53.05",
"2017-08-30T14:40:45.34"
],
"NumScrapsList": [
0,
3,
1,
]
}
}
outputs = [dict(zip(resp['Outputs'].keys(), e))
for e in zip(*resp['Outputs'].values())]
pprint(outputs)
Result:
[{'Actual': '2017-08-29T14:37:47.137',
'NumScrapsList': 0,
'Start': '2017-08-29T14:36:12.42'},
{'Actual': '2017-08-30T13:07:09.563',
'NumScrapsList': 3,
'Start': '2017-08-30T12:59:53.05'},
{'Actual': '2017-08-30T14:41:29.023',
'NumScrapsList': 1,
'Start': '2017-08-30T14:40:45.34'}]
CodePudding user response:
Perhaps you can try something like this:
response = {"Outputs": {
"Actual": [
"2017-08-29T14:37:47.137",
"2017-08-30T13:07:09.563",
"2017-08-30T14:41:29.023"
],
"Start": [
"2017-08-29T14:36:12.42",
"2017-08-30T12:59:53.05",
"2017-08-30T14:40:45.34"
],
"NumScrapsList": [0, 3, 4]
}
}
temp = response["Outputs"]
final = {"Outputs": []}
for i in range(len(temp["NumScrapsList"])):
entry = {"NumScrapsList": temp["NumScrapsList"][i],
"Actual": temp["Actual"][i],
"Start": temp["Start"][i]
}
final["Outputs"].append(entry)
print(final)
Output:
{ 'Outputs': [ { 'NumScrapsList': 0,
'Actual': '2017-08-29T14:37:47.137',
'Start': '2017-08-29T14:36:12.42'
},
{ 'NumScrapsList': 3,
'Actual': '2017-08-30T13:07:09.563',
'Start': '2017-08-30T12:59:53.05'
},
{
'NumScrapsList': 4,
'Actual': '2017-08-30T14:41:29.023',
'Start': '2017-08-30T14:40:45.34'
}
]
}