0

I'm trying to parse key value pairs(fname and jobcode) after performing get request. What's the best way to parse key value pairs to perform tasks?

Below is my get request response on

response = requests.get('url')

Result:

[
    {
        "fname": "James",
        "jobcode": "51202"
    },
    {
        "fname": "Jim",
        "jobcode": "32304"
    }
]

Tried it this way, and got AttributeError: 'list' object has no attribute 'items'.

json_data = json.loads(response.text)
print json_data
for key, value in json_data.items():
    print key, value

I want to translate it into a list like [James, 51202], [Jim, 32304] so that I can easily use. Or, I'd like to just get key value pairs so that I can iterate over them.

martineau
  • 119,623
  • 25
  • 170
  • 301
user5977290
  • 31
  • 2
  • 7

1 Answers1

0

Supposed that:

response = [
    {
        "fname": "James",
        "jobcode": "51202"
    },
    {
        "fname": "Jim",
        "jobcode": "32304"
    }
]

If you want to couple the elements in the dictionary you can do:

listdata = [[el[1] for el in dd.items()] for dd in response]

listdata is [['James', '51202'], ['Jim', '32304']]

Or if you prefer a plain list (no nested lists) with all the data:

listdata = [el[1] for dd in response for el in dd.items()]

In this case listdata is ['James', '51202', 'Jim', '32304'].

Valentino
  • 7,291
  • 6
  • 18
  • 34
  • Why do I get [u'James'], [u'51202'] ? – user5977290 Feb 09 '19 at 22:21
  • Because your strings are unicode (that is the meaning of the 'u' before the string). In general is not a problem, the 'u' is there in the string representation to specify that is a unicode string. But the string itself does not have any prefixed u (for example, if you write the string back in a file, there is no 'u'). Have a look [here](https://stackoverflow.com/questions/13940272/python-json-loads-returns-items-prefixing-with-u) too. – Valentino Feb 09 '19 at 22:32