小编AWa*_*ton的帖子

Python:将JSON字典值写入JSON文件

我正在尝试:

  1. 从字典的JSON列表中加载数据
  2. 将每个字典中特定键的值写入文件

但是,当我尝试将密钥对转储到新的.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)

python json dictionary dump python-3.x

2
推荐指数
1
解决办法
4253
查看次数

标签 统计

dictionary ×1

dump ×1

json ×1

python ×1

python-3.x ×1