Take a look at the json module. More specifically the 'Decoding JSON:' section.
import json
import requests
response = requests.get() # api call
users = json.loads(response.text)
for user in users:
print(user['id'])
Answer from Jim Wright on Stack OverflowTake a look at the json module. More specifically the 'Decoding JSON:' section.
import json
import requests
response = requests.get() # api call
users = json.loads(response.text)
for user in users:
print(user['id'])
You can try like below to get the values from json response:
import json
content=[{
"username": "admin",
"first_name": "",
"last_name": "",
"roles": "system_admin system_user",
"locale": "en",
"delete_at": 0,
"update_at": 1511335509393,
"create_at": 1511335500662,
"auth_service": "",
"email": "[email protected]",
"auth_data": "",
"position": "",
"nickname": "",
"id": "pbjds5wmsp8cxr993nmc6ozodh"
}, {
"username": "chatops",
"first_name": "",
"last_name": "",
"roles": "system_user",
"locale": "en",
"delete_at": 0,
"update_at": 1511335743479,
"create_at": 1511335743393,
"auth_service": "",
"email": "[email protected]",
"auth_data": "",
"position": "",
"nickname": "",
"id": "akxdddp5p7fjirxq7whhntq1nr"
}]
for item in content:
print("Name: {}\nEmail: {}\nID: {}\n".format(item['username'],item['email'],item['id']))
Output:
Name: admin
Email: [email protected]
ID: pbjds5wmsp8cxr993nmc6ozodh
Name: chatops
Email: [email protected]
ID: akxdddp5p7fjirxq7whhntq1nr
Python Parse JSON array - Stack Overflow
python - Create array of json objects using for loops - Stack Overflow
Creating JSON Array of data with python
Parsing muilti dimensional Json array to Python - Stack Overflow
Videos
You're trying to read the string "data.txt". What you want is to open and read the file.
import json
with open('data.txt', 'r') as data_file:
json_data = data_file.read()
data = json.loads(json_data)
Try:
data = json.load(open("data.txt", 'r'))
json.loads interprets a string as JSON data, while json.load takes a file object and reads it, then interprets it as JSON.
In your for loop statement, Each item in json_array is a dictionary and the dictionary does not have a key store_details. So I modified the program a little bit
import json
input_file = open ('stores-small.json')
json_array = json.load(input_file)
store_list = []
for item in json_array:
store_details = {"name":None, "city":None}
store_details['name'] = item['name']
store_details['city'] = item['city']
store_list.append(store_details)
print(store_list)
If you arrived at this question simply looking for a way to read a json file into memory, then use the built-in json module.
with open(file_path, 'r') as f:
data = json.load(f)
If you have a json string in memory that needs to be parsed, use json.loads() instead:
data = json.loads(my_json_string)
Either way, now data is converted into a Python data structure (list/dictionary) that may be (deeply) nested and you'll need Python methods to manipulate it.
If you arrived here looking for ways to get values under several keys as in the OP, then the question is about looping over a Python data structure. For a not-so-deeply-nested data structure, the most readable (and possibly the fastest) way is a list / dict comprehension. For example, for the requirement in the OP, a list comprehension does the job.
store_list = [{'name': item['name'], 'city': item['city']} for item in json_array]
# [{'name': 'Mall of America', 'city': 'Bloomington'}, {'name': 'Tempe Marketplace', 'city': 'Tempe'}]
Other types of common data manipulation:
For a nested list where each sub-list is a list of items in the
json_array.store_list = [[item['name'], item['city']] for item in json_array] # [['Mall of America', 'Bloomington'], ['Tempe Marketplace', 'Tempe']]For a dictionary of lists where each key-value pair is a category-values in the
json_array.store_data = {'name': [], 'city': []} for item in json_array: store_data['name'].append(item['name']) store_data['city'].append(item['city']) # {'name': ['Mall of America', 'Tempe Marketplace'], 'city': ['Bloomington', 'Tempe']}For a "transposed" nested list where each sub-list is a "category" in
json_array.store_list = list(store_data.values()) # [['Mall of America', 'Tempe Marketplace'], ['Bloomington', 'Tempe']]
You need to maintain two lists for scores and titles and append all the data to those lists, instead of printing, and then zip those lists along with list comprehension to get the desired output as :
import json
scores, titles = [], []
for line in games_html.findAll('div', class_="product_score"):
scores.append(line.getText(strip=True))
for line in games_html.findAll('a'):
titles.append(line.getText(strip=True))
score_titles = [{"Title": t, "Score": s} for t, s in zip(titles, scores)]
print score_titles
# Printing in JSON format
print json.dumps(score_titles)
As ZdaR's post illustrates, to create a json, you need to build the corresponding Python data structure (lists for json arrays, dictionaries for json objects) and serialize it at the end. So the question is almost the same as how to create a list in a loop, because after creating the list, what remains is serialization which is as simple as json.loads(data).
The task in the OP can be done in two loops:
data = [{'Title': line.getText(strip=True)} for line in games_html.findAll('a')]
for i, line in enumerate(games_html.findAll('div', class_="product_score")):
data[i]['Score'] = line.getText(strip=True)
# serialize to json array
j = json.dumps(data)
# or write to a file
with open('data.json', 'w') as f:
json.dump(data, f)
After you parse the JSON, you will end up with a Python dict. So, suppose the above JSON is in a string named input_data:
import json
# This converts from JSON to a python dict
parsed_input = json.loads(input_data)
# Now, all of your static variables are referenceable as keys:
secret = parsed_input['secret']
minutes = parsed_input['minutes']
link = parsed_input['link']
# Plus, you can get your bookmark collection as:
bookmark_collection = parsed_input['bookmark_collection']
# Print a list of names of the bookmark collections...
print bookmark_collection.keys() # Note this contains sublinks, so remove it if needed
# Get the name of the Boarding Pass bookmark:
print bookmark_collection['boarding_pass']['name']
# Print out a list of all bookmark links as:
# Boarding Pass
# * 1: http://www.1.com/
# * 2: http://www.2.com/
# ...
for bookmark_definition in bookmark_collection.values():
# Skip sublinks...
if bookmark_definition['name'] == 'sublinks':
continue
print bookmark_definition['name']
for bookmark in bookmark_definition['bookmarks']:
print " * %(name)s: %(link)s" % bookmark
# Get the sublink definition:
sublinks = parsed_input['bookmark_collection']['sublinks']
# .. and print them
print sublinks['name']
for link in sublinks['link']:
print ' *', link
Hmm, doesn't json.loads do the trick?
For example, if your data is in a file,
import json
text = open('/tmp/mydata.json').read()
d = json.loads(text)
# first level fields
print d['minutes'] # or 'secret' or 'link'
# the names of each of bookmark_collections's items
print d['bookmark_collection'].keys()
# the sublinks section, as a dict
print d['bookmark_collection']['sublinks']
The output of this code (given your sample input above) is:
20
[u'sublinks', u'free_link', u'boarding_pass']
{u'link': [u'http://www.1.com', u'http://www.2.com', u'http://www.3.com'], u'name': u'sublinks'}
Which, I think, gets you what you need?
Hi everyone. I'm really, really confused about parsing a JSON array.
For my script, I'll need to use a reverse geocoder, and I've decided to use Google's. I'm requesting a JSON, and it's returning this: https://developers.google.com/maps/documentation/geocoding/intro#reverse-example.
What I can't seem to figure out is the proper way of parsing it. I'm trying to extract the long_name in a few different types (for this example, let's say route, neighborhood, and administrative_area_level_2), and pass each long name for each type as their own string.
I'm completely lost on how to go about parsing this. I've tried json.loads, and doing a bunch of other things that fail in a "list indices must be integer", or unexpected results.
Right now, this is the nieve code I'm using to at least print long_name (about 30 times):
reverse_json = json.load(reader(reverseJSON))
# Excuse the debugging
print(reverse_json)
for data in reverse_json['results']:
address = data['address_components']
for data in address:
address = data['long_name']
print(address)And if I add on this to the final for loop:
if data['types'] == "['route']":
address = data['long_name']
print(address)I get nothing.
json.loads doesn't help, either. It just results in
TypeError: the JSON object must be str, bytes or bytearray, not 'StreamReader'
So, I'm stuck with trying to parse a JSON array, and to have "long_name" become a certain variable if a certain type occurs. It's confusing to me, hopefully it isn't to you.
A simple explanation and help would be appreciated.
You can use a list comprehension to produce a list of dictionaries, then convert that:
json_string = json.dumps([ob.__dict__ for ob in list_name])
or use a default function; json.dumps() will call it for anything it cannot serialise:
def obj_dict(obj):
return obj.__dict__
json_string = json.dumps(list_name, default=obj_dict)
The latter works for objects inserted at any level of the structure, not just in lists.
Personally, I'd use a project like marshmallow to handle anything more complex; e.g. handling your example data could be done with
from marshmallow import Schema, fields
class ObjectSchema(Schema):
city = fields.Str()
name = fields.Str()
object_schema = ObjectSchema()
json_string = object_schema.dumps(list_name, many=True)
Similar to @MartijnPieters' answer, you can use the json.dumps default parameter with a lambda, if you don't want to have to create a separate function:
json.dumps(obj, default = lambda x: x.__dict__)
import json
array = '{"fruits": ["apple", "banana", "orange"]}'
data = json.loads(array)
print(data['fruits'])
# the print displays:
# ['apple', 'banana', 'orange']
You had everything you needed. data will be a dict, and data['fruits'] will be a list
Tested on Ideone.
import json
array = '{"fruits": ["apple", "banana", "orange"]}'
data = json.loads(array)
fruits_list = data['fruits']
print fruits_list