she*_*158 270 python json dictionary python-2.7
r = {'is_claimed': 'True', 'rating': 3.5}
r = json.dumps(r)
file.write(str(r['rating']))
Run Code Online (Sandbox Code Playgroud)
我无法在json中访问我的数据.我究竟做错了什么?
TypeError: string indices must be integers, not str
Run Code Online (Sandbox Code Playgroud)
Ima*_*deh 429
json.dumps()将字典转换为str对象,而不是json(dict)对象!所以你必须将你的str加载到dict中才能通过使用str方法来使用它
请参阅json(dict)保存方法和str检索方法.
这是代码示例,可以帮助您更好地理解它:
import json
r = {'is_claimed': 'True', 'rating': 3.5}
r = json.dumps(r)
loaded_r = json.loads(r)
loaded_r['rating'] #Output 3.5
type(r) #Output str
type(loaded_r) #Output dict
Run Code Online (Sandbox Code Playgroud)
Tim*_*Tim 36
json.dumps()返回python dict的JSON字符串表示形式.查看文档
你不能这样做,r['rating']因为r是一个字符串,而不是一个字典
也许你的意思是
r = {'is_claimed': 'True', 'rating': 3.5}
json = json.dumps(r) # note i gave it a different name
file.write(str(r['rating']))
Run Code Online (Sandbox Code Playgroud)
Mil*_*vić 12
json.dumps() 用于解码 JSON 数据json.loads 将一个字符串作为输入并返回一个字典作为输出。json.dumps 以字典作为输入并返回一个字符串作为输出。import json
# initialize different data
str_data = 'normal string'
int_data = 1
float_data = 1.50
list_data = [str_data, int_data, float_data]
nested_list = [int_data, float_data, list_data]
dictionary = {
'int': int_data,
'str': str_data,
'float': float_data,
'list': list_data,
'nested list': nested_list
}
# convert them to JSON data and then print it
print('String :', json.dumps(str_data))
print('Integer :', json.dumps(int_data))
print('Float :', json.dumps(float_data))
print('List :', json.dumps(list_data))
print('Nested List :', json.dumps(nested_list, indent=4))
print('Dictionary :', json.dumps(dictionary, indent=4)) # the json data will be indented
Run Code Online (Sandbox Code Playgroud)
输出:
String : "normal string"
Integer : 1
Float : 1.5
List : ["normal string", 1, 1.5]
Nested List : [
1,
1.5,
[
"normal string",
1,
1.5
]
]
Dictionary : {
"int": 1,
"str": "normal string",
"float": 1.5,
"list": [
"normal string",
1,
1.5
],
"nested list": [
1,
1.5,
[
"normal string",
1,
1.5
]
]
}
Run Code Online (Sandbox Code Playgroud)
| Python | JSON |
|:--------------------------------------:|:------:|
| dict | object |
| list, tuple | array |
| str | string |
| int, float, int- & float-derived Enums | number |
| True | true |
| False | false |
| None | null |
Run Code Online (Sandbox Code Playgroud)
nested_dictionary = {
'one': nested_list,
'two': dictionary,
}
json_dict = {'Nested Dictionary': nested_dictionary,
'Multiple':[nested_dictionary, nested_dictionary, nested_dictionary]
}
with open("test_nested.json", "w") as outfile:
json.dump(json_dict, outfile, indent=4, sort_keys=False)
Run Code Online (Sandbox Code Playgroud)
图表反应
输出到 test_nested.json
{
"Nested Dictionary": {
"one": [
1,
1.5,
[
"normal string",
1,
1.5
]
],
"two": {
"int": 1,
"str": "normal string",
"float": 1.5,
"list": [
"normal string",
1,
1.5
],
"nested list": [
1,
1.5,
[
"normal string",
1,
1.5
]
]
}
},
"Multiple": [
{
"one": [
1,
1.5,
[
"normal string",
1,
1.5
]
],
"two": {
"int": 1,
"str": "normal string",
"float": 1.5,
"list": [
"normal string",
1,
1.5
],
"nested list": [
1,
1.5,
[
"normal string",
1,
1.5
]
]
}
},
{
"one": [
1,
1.5,
[
"normal string",
1,
1.5
]
],
"two": {
"int": 1,
"str": "normal string",
"float": 1.5,
"list": [
"normal string",
1,
1.5
],
"nested list": [
1,
1.5,
[
"normal string",
1,
1.5
]
]
}
},
{
"one": [
1,
1.5,
[
"normal string",
1,
1.5
]
],
"two": {
"int": 1,
"str": "normal string",
"float": 1.5,
"list": [
"normal string",
1,
1.5
],
"nested list": [
1,
1.5,
[
"normal string",
1,
1.5
]
]
}
}
]
}
Run Code Online (Sandbox Code Playgroud)
class 实例到 JSONclass Foo(object):
def __init__(
self,
data_str,
data_int,
data_float,
data_list,
data_n_list,
data_dict,
data_n_dict):
self.str_data = data_str
self.int_data = data_int
self.float_data = data_float
self.list_data = data_list
self.nested_list = data_n_list
self.dictionary = data_dict
self.nested_dictionary = data_n_dict
foo = Foo(
str_data,
int_data,
float_data,
list_data,
nested_list,
dictionary,
nested_dictionary)
# Because the JSON object is a Python dictionary.
result = json.dumps(foo.__dict__, indent=4)
# See table above.
# or with built-in function that accesses .__dict__ for you, called vars()
# result = json.dumps(vars(foo), indent=4)
print(result) # same as before
Run Code Online (Sandbox Code Playgroud)
class Bar:
def toJSON(self):
return json.dumps(self, default=lambda o: o.__dict__,
sort_keys=False, indent=4)
bar = Bar()
bar.web = "Stackoverflow"
bar.type = "Knowledge"
bar.is_the_best = True
bar.user = Bar()
bar.user.name = "Milovan"
bar.user.age = 34
print(bar.toJSON())
Run Code Online (Sandbox Code Playgroud)
图表反应
输出:
{
"web": "Stackoverflow",
"type": "Knowledge",
"is_the_best": true,
"user": {
"name": "Milovan",
"age": 34
}
}
Run Code Online (Sandbox Code Playgroud)
小智 6
您可以通过在默认字典中声明新字典来在上面的示例中创建嵌套字典。
import json
dictionary = {
'fruit':{"Grapes": "10","color": "green"},
'vegetable':{"chilli": "4","color": "red"},
}
result = json.dumps(dictionary, indent = 3)
Run Code Online (Sandbox Code Playgroud)
打印(结果)
在这里,我使用了 indent=3
参考: https: //favtutor.com/blogs/dict-to-json-python