Search code examples
pythonjsonpandaspython-requestsdictionary-comprehension

Handling requests response


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


Solution

  • 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'}]