Python 如何从json文件中获取密钥对值?
data=“[{”id:“abc”,content:“Bye”,“child:[{”id:“dsd”,“parent id:“abc”,“content:“dds”}],{”id:“xcv”,content:“hello”}]” 我想提取“再见”和“你好”,但我偶然发现了这个错误。我想知道如何循环Python 如何从json文件中获取密钥对值?,python,json,dictionary,Python,Json,Dictionary,data=“[{”id:“abc”,content:“Bye”,“child:[{”id:“dsd”,“parent id:“abc”,“content:“dds”}],{”id:“xcv”,content:“hello”}]” 我想提取“再见”和“你好”,但我偶然发现了这个错误。我想知道如何循环 TypeError Traceback (most recent call last) <ipython-input-2-1aa8
TypeError Traceback (most recent call last)
<ipython-input-2-1aa8088c77a7> in <module>
46
47 for e in parsed_json:
---> 48 print (e["content"])
49
50
TypeError: string indices must be integer
TypeError回溯(最近一次调用)
在里面
46
47对于解析的_json中的e:
--->48打印(e[“内容”])
49
50
TypeError:字符串索引必须是整数
不要使用json.dump
将字符串写入文件。使用它将数据结构(列表、字典等)写入文件
因此,不要将数据
变量的原始值放在引号内
此外,数据中缺少一些引号(abc
缺少结束引号,xcv
缺少两个引号)
您必须提供一个。那
数据
真的是代码的一部分吗?整个数据
真的包含在中吗?
?
TypeError Traceback (most recent call last)
<ipython-input-2-1aa8088c77a7> in <module>
46
47 for e in parsed_json:
---> 48 print (e["content"])
49
50
TypeError: string indices must be integer
import json
data = [{"id":"abc", "content":"Bye", "child": [{"id":"dsd", "parent id":"abc", "content":"dds"}]},
{"id":"xcv", "content":"hello"}]
with open("data.json","w") as f:
json.dump(data, f)
# reads it back
with open("data.json","r") as f:
parsed_json = json.load(f)
for e in parsed_json:
print (e["content"])