Reputation: 300
All,
I am new to JSON and python world. I'm trying to parse JSON data located here. I was able to parse JSON data using below code. My question is when I tried to check the type of my 'jsonData' object, it turned out that it is a list instead of Dictionary
. Most of JSON data I saw online consists of type dictionary
. So it is ok to have list as a type instead of Dictionary ? or do I need to convert my 'jsonData' object into Dictionary, if yes how can I achieve it ?
Code for parsing
response=urllib.request.urlopen(url)
json_string=response.read().decode('utf-8')
parsed_json=json.loads(json_string)
jsonData =parsed_json
Thanks in advance,
Upvotes: 5
Views: 2399
Reputation: 111
Welcome to the JSON and Python world. First things first, you can make the HTTP request and parse the response in fewer lines:
# We will use requests library instead of urllib. See Ref. 1.
import requests
url = 'http://api.population.io/1.0/population/2010/United%20States/?format=json'
response = requests.get(url) # Make an HTTP GET request
jsonData = response.json() # Read the response data in JSON format
print(type(jsonData)) # prints <type 'list'>
for x in jsonData:
print(type(x)) # prints <type 'dict'>
Why does it say jsonData
is a list? Because jsonData
is a list.
Why does it say every x
is a dictionary? Because every x
is a dictionary.
Look closely at the data located here. It starts and ends with [
and ]
respectively. Inside the [
and ]
, there are pairs of {
and }
.
list = [] # this is how you declare lists in python
dict = {} # this is how you declare dictionaries in python
So, your JSON data is being parsed correctly. It is a JSON list of JSON objects. See Ref. 2.
References:
Upvotes: 4