[英]python index json array
我有一个 json 文件,其中包含 15000 多行,如下所示;
{
"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"
]
}
但是我得到错误: raise JSONDecodeError("Extra data", s, end)
如果我把它变成一个字符串,它会起作用,比如:my_str = '[{"address": "user address"}, {"info1": "some information", "more information"}]' print(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 文件相互连接。 要阅读它,您必须更底层:
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']}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.