json.load loads from a file-like object. You either want to use json.loads:
json.loads(data)
Or just use json.load on the request, which is a file-like object:
json.load(request)
Also, if you use the requests library, you can just do:
import requests
json = requests.get(url).json()
Answer from Blender on Stack Overflowconverting JSON to string in Python - Stack Overflow
How to turn JSON into objects in python?
Parsing a string representing json to json, but some string values contain double quotes
json.load converting double quotes to single quotes
Python displays strings as single-quoted. So in the interpreter:
>>> "dog" 'dog' >>> str(123) '123'
If you mean how to format it properly to serve json upon a GET request, you can transform python data back into a json string with json.dumps(data).
Videos
json.dumps() is much more than just making a string out of a Python object, it would always produce a valid JSON string (assuming everything inside the object is serializable) following the Type Conversion Table.
For instance, if one of the values is None, the str() would produce an invalid JSON which cannot be loaded:
>>> data = {'jsonKey': None}
>>> str(data)
"{'jsonKey': None}"
>>> json.loads(str(data))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 382, in raw_decode
obj, end = self.scan_once(s, idx)
ValueError: Expecting property name: line 1 column 2 (char 1)
But the dumps() would convert None into null making a valid JSON string that can be loaded:
>>> import json
>>> data = {'jsonKey': None}
>>> json.dumps(data)
'{"jsonKey": null}'
>>> json.loads(json.dumps(data))
{u'jsonKey': None}
There are other differences. For instance, {'time': datetime.now()} cannot be serialized to JSON, but can be converted to string. You should use one of these tools depending on the purpose (i.e. will the result later be decoded).
I have never done this in python before but I'm pretty sure I could turn the retrieved JSON into a dictionary, but what is the best practice to convert the retrieved JSON into a class with its properties being items from the JSON.
So for example
{
"name":"Harry",
"job":"Mechanic"
}would yield
class Person:
def __init__(self, name, job):
self.name = name
self.job = jobAlso is there an easier way to do this.. something like a factory constructor.. ?