john doe
john doe

Reputation: 2253

Problems while reformating this json output?

I am calling an API with requests as follows:

def get_data(text, url='api.com'):
    r = requests.get(url,
                     params={'key': '<My KEY>',
                             'in': text
                             'fj': 'm'})
    if r.status_code != requests.codes.ok:
        return np.nan
    return r.json()

Each row looks like this:

{'A': [{'param0': 'a',
   'param1': 'b',
   'param2': '342',
   'param3': '$ 2342',
   'param4': '234',
   'param5': '555'}],
 'status': {'code': '0', 'credits': '1', 'msg': 'OK'}}

How can I transform each column in to a tuple like this:

[('param0','a'), ('param1','b'), ('param2', '342'), ('param3', '$ 2342'), ('param5', '555')]

At first instance I tried to parse the above output, however I can not access since I get:

TypeError: the JSON object must be str, not 'float'

Any idea of how to get the list of tuples?.

Upvotes: 1

Views: 48

Answers (1)

宏杰李
宏杰李

Reputation: 12168

d = {'A': [{'param0': 'a',
   'param1': 'b',
   'param2': '342',
   'param3': '$ 2342',
   'param4': '234',
   'param5': '555'}],
 'status': {'code': '0', 'credits': '1', 'msg': 'OK'}}

[i for i in d['A'][0].items()]

out:

[('param1', 'b'),
 ('param5', '555'),
 ('param0', 'a'),
 ('param4', '234'),
 ('param3', '$ 2342'),
 ('param2', '342')]

There's also a builtin JSON decoder, in case you're dealing with JSON data:

>>> import requests

>>> r = requests.get('https://api.github.com/events')
>>> r.json()
[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...

Upvotes: 1

Related Questions