1

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?.

john doe
  • 2,233
  • 7
  • 37
  • 58

1 Answers1

1
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/...
宏杰李
  • 11,820
  • 2
  • 28
  • 35
  • 1
    Thanks, I got this error: `ValueError: malformed node or string:`. I guess is an ecoding issue... since the type of the function output is a dict – john doe Jan 11 '17 at 05:04
  • 1
    @john doe http://stackoverflow.com/questions/14611352/malformed-string-valueerror-ast-literal-eval-with-string-representation-of-tup. this error is off topic of this question. – 宏杰李 Jan 11 '17 at 05:10
  • Thanks again!... I tried to use the ast and still the same, what can I do? – john doe Jan 11 '17 at 05:19
  • 1
    @john doe you should post another question about it, it's hard to answer a question in comment. and please accept this answer to close this question. – 宏杰李 Jan 11 '17 at 05:25
  • I tried to reformat the output of the json, check my update! – john doe Jan 11 '17 at 05:35
  • @john doe r.json() will return a python object, no need to decode it . – 宏杰李 Jan 11 '17 at 05:39
  • Thanks, from the start I tried the json built in, and I have the aforementioned issue – john doe Jan 11 '17 at 05:52