我正在尝试:
但是,当我尝试将密钥对转储到新的.json文件时,它仅输出最后一个字典密钥对。有人知道如何遍历每个字典并附加密钥对吗?我尝试了几种方法,但似乎无法弄清我所缺少的内容和位置。
这是我的代码:
with open(join(dirname(__file__),'text.json')) as tone_json:
python_obj = json.load(tone_json) #read file object into string
my_list = python_obj["data"] #assign list name to string
for dictionary in my_list: #loop through dictionaries in list
for key,value in dictionary.items(): #loop through key pairs in dictionaries
if key == "text":
with open('comments.json', 'w') as f:
json.dump("{}: {}".format(key,value), f) #write key pair objects as json formatted stream to json file
f.write('\n')
Run Code Online (Sandbox Code Playgroud)
我的JSON文件的示例:
{
"data": [
{
"text": "apple",
"created_time": "2017-12-23",
"comment_count": 154,
"like_count": …Run Code Online (Sandbox Code Playgroud)