python 索引 json 数组
python index json array
我有一个包含 15000 多行的 json 文件,如下所示;
{
"address": [
"user address"
]
}{
"purchase": [
"details"
]
}{
"info1": [
"some information",
"other information",
"more information"
],
"info2": [
"something else"
]
}
我想做类似的事情:
f = open('my_file.json',)
data = json.load(f)
print(data[2])
其中 index[2] 将打印最后一组大括号之间的所有内容,因此:
{
"info1": [
"some information",
"other information",
"more information"
],
"info2": [
"something else"
]
}
但是我得到错误:
提高 JSONDecodeError(“额外数据”,s,结束)
如果我把它变成一个字符串就可以了,比如:
my_str = '[{"address": "用户地址"}, {"info1": "一些信息", "更多信息"}]'
打印(my_str[2])
是否可以像上面那样读取 json 文件并打印 [2]?
根据下面的评论,如果我这样做:
with open('my_file.json', 'r') as f:
my_list = list(f)
values_list = list(my_list)
a_value = values_list
print(a_value[10])
它打印“一些信息”。
json.load
和json.loads
需要有一个正确的JSON,从头到尾。您的文件不是正确的 JSON 文件;它似乎是一些 JSON 文件相互连接。要看的话,你还得再多一点low-level:
with open('my_file.json', 'rt') as f:
json_doc = f.read().strip()
decoder = json.JSONDecoder()
data = []
while json_doc:
value, cont = decoder.raw_decode(json_doc)
data.append(value)
json_doc = json_doc[cont:]
print(data[2])
# => {'info1': ['some information', 'other information', 'more information'], 'info2': ['something else']}
我有一个包含 15000 多行的 json 文件,如下所示;
{
"address": [
"user address"
]
}{
"purchase": [
"details"
]
}{
"info1": [
"some information",
"other information",
"more information"
],
"info2": [
"something else"
]
}
我想做类似的事情:
f = open('my_file.json',)
data = json.load(f)
print(data[2])
其中 index[2] 将打印最后一组大括号之间的所有内容,因此:
{
"info1": [
"some information",
"other information",
"more information"
],
"info2": [
"something else"
]
}
但是我得到错误: 提高 JSONDecodeError(“额外数据”,s,结束)
如果我把它变成一个字符串就可以了,比如: my_str = '[{"address": "用户地址"}, {"info1": "一些信息", "更多信息"}]' 打印(my_str[2])
是否可以像上面那样读取 json 文件并打印 [2]?
根据下面的评论,如果我这样做:
with open('my_file.json', 'r') as f:
my_list = list(f)
values_list = list(my_list)
a_value = values_list
print(a_value[10])
它打印“一些信息”。
json.load
和json.loads
需要有一个正确的JSON,从头到尾。您的文件不是正确的 JSON 文件;它似乎是一些 JSON 文件相互连接。要看的话,你还得再多一点low-level:
with open('my_file.json', 'rt') as f:
json_doc = f.read().strip()
decoder = json.JSONDecoder()
data = []
while json_doc:
value, cont = decoder.raw_decode(json_doc)
data.append(value)
json_doc = json_doc[cont:]
print(data[2])
# => {'info1': ['some information', 'other information', 'more information'], 'info2': ['something else']}