问题描述
我有以下要使用python 3解析的json对象:
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}
}
我正在使用以下python代码来解析对象:
I am using the following python code to parse the object:
import json
def greetCustomer(customerData):
response = json.loads(customerData)
我遇到以下错误:
推荐答案
customerData = {
"Joe": {"visits": 1},
"Carol": {"visits": 2},
"Howard": {"visits": 3},
"Carrie": {"visits": 4}
}
是定义字典的Python代码.如果你有
is Python code that defines a dictionary. If you had
customerJSON = """{
"Joe": {"visits": 1},
"Carol": {"visits": 2},
"Howard": {"visits": 3},
"Carrie": {"visits": 4}
}"""
您将拥有一个包含要解析的JSON对象的字符串. (是的,Python语法和JSON语法之间有很多重叠之处.
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)
可以通过.
不过请注意,并非 all 个有效的Python都类似于有效的JSON.
Note, though, that not all valid Python resembles valid JSON.
以下是对同一对象进行编码的三种不同的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
]
您可以观察到all(json.loads(x) == {'foo': 'bar'} for x in json_strs)
是真实的,因为所有三个字符串都编码相同的Python字典.
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.
相反,我们可以定义三个Python字典,其中前两个是相同的.
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
]
dicts[0] == dicts[1] == json.loads(json_str)
确实是.然而,dicts[2] == json.loads(json_str)
仅在foo == "foo"
时为真.
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"
.
这篇关于尝试使用python 3加载JSON对象时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!