I have the following json object I am trying to parse with python 3:
customerData = {
"Joe": {"visits": 1},
"Carol": {"visits": 2},
"Howard": {"visits": 3},
"Carrie": {"visits": 4}
}
I am using the following python code to parse the object:
import json
def greetCustomer(customerData):
response = json.loads(customerData)
I'm getting the following error:
TypeError: the JSON object must be str, bytes or bytearray, not 'dict'
customerData = {
"Joe": {"visits": 1},
"Carol": {"visits": 2},
"Howard": {"visits": 3},
"Carrie": {"visits": 4}
}
is Python code that defines a dictionary. If you had
customerJSON = """{
"Joe": {"visits": 1},
"Carol": {"visits": 2},
"Howard": {"visits": 3},
"Carrie": {"visits": 4}
}"""
you would have a string that contains a JSON object to be parsed. (Yes, there is a lot of overlap between Python syntax and JSON syntax.
assert customerData == json.loads(customerJSON)
would pass.)
Note, though, that not all valid Python resembles valid JSON.
Here are three different JSON strings that encode the same object:
json_strs = [
"{'foo': 'bar'}", # invalid JSON, uses single quotes
'{"foo": "bar"}', # valid JSON, uses double quotes
'{foo: "bar"}' # valid JSON, quotes around key can be omitted
]
You can observe that all(json.loads(x) == {'foo': 'bar'} for x in json_strs)
is true, since all three strings encode the same Python dict.
Conversely, we can define three Python dicts, the first two of which are identical.
json_str = json_strs[0] # Just to pick one
foo = ... # Some value
dicts = [
{'foo': 'bar'}, # valid Python dict
{"foo": "bar"}, # valid Python dict
{foo: "bar"} # valid Python dict *if* foo is a hashable value
# and not necessarily
]
It is true that dicts[0] == dicts[1] == json.loads(json_str)
. However, dicts[2] == json.loads(json_str)
is only true if foo == "foo"
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments