so i would like to list the first value of users json i get from making an rest api call with python so that the response is like this :
0 :"XXX-XXX", 1 :"DDD-DDD", 2: "KKK-KKK", 3 :"UUU-UUU"
Json Data from API call:
"XXX-XXX":{
"Info":{
"ID":"08",
"Created": "2021-07-10",
"Plan": "Basic"}},
"DDD-DDD":{
"Info":{
"ID":"04",
"Created": "2021-07-11",
"Plan": "Prime"}}
},
"KKK-KKK":{
"Info":{
"ID":"02",
"Created": "2021-07-11",
"Plan": "Prime"}}
},
"UUU-UUU":{
"Info":{
"ID":"13",
"Created": "2021-07-11",
"Plan": "Prime"}}
}
}```
CodePudding user response:
OK, so the solution is simple. Python includes a JSON module. So first you load the JSON as a Python dictionary using the load() method, then call the keys() method on the dictionary to get an iterable containing the keys. An iterable means you can iterate over it as if it were a list, but if you absolutely need a list, you can convert that object to a list.
Here's some code:
import json
json_string = """ { "X": {"name":"hi"},"Y": {name:"yo"}}
"""
dictionary = json.loads(json_string) # get a dictionary from the JSON
keys = dictionary.keys() # get the keys of the dictionary
for key in keys: #iterate over keys
print(key)
key_list = list(keys) # converts keys to a Python list