Sam
Sam

Reputation: 2331

Opening a Json File From Google API's In Python3

I would like to open a json file in python as an object that I can manipulate and work with

I have a json file than contains text like the following

{'geocoded_waypoints': [{'geocoder_status': 'OK', 'place_id': 'ChIJtxsqpbgEdkgRSCY1a5fQpDA', 'types': ['airport', 'establishment', 'point_of_interest']}, {'geocoder_status': 'OK', 'place_id': 'ChIJdd4hrwug2EcRmSrV3Vo6llI', 'types': ['locality', 'political']}], 'routes': ......

...

I received this json text from the google transit api, I know that json doesn't look like the above text, but that's what google transit gives me so thats what I have to work with.

I've tried this method,

>>> data = json.load(open('gmap_routes.json'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/__init__.py", line 299, in load
    parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/decoder.py", line 355, in raw_decode
    obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

And this method where I tried to fix the unicode characters in it but it would not work

>>> import json
>>> with open("gmap_routes.json") as f:
...     json.load(f.encode("ascii","replace"))
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
AttributeError: '_io.TextIOWrapper' object has no attribute 'encode'

I also tried python2 for a while and got similar results, so I just went back to python3

Upvotes: 0

Views: 340

Answers (1)

Robert Hamilton
Robert Hamilton

Reputation: 91

Yeah, those "'" characters are the problem.

You'll need to perform a replace operation on the contents of the file by calling file.read(), not the file itself - this will return a string so use json.loads instead of json.load on the result:

    import json
    file = open("some_file.json")
    with file as f:
    data = json.loads(f.read().replace("'", "\""))

Upvotes: 1

Related Questions