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)
Answer from Agustín Lado on Stack OverflowYou'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.
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.
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