Python:将JSON字典值写入JSON fi

2024-04-25 06:25:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图:

  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')

我的JSON文件示例:

{ 
    "data": [
    {
        "text": "apple",
        "created_time": "2017-12-23",
        "comment_count": 154,
        "like_count": 856,
        "id": "1015595299xxxxx"
    },
    {
        "text": "orange",
        "created_time": "2017-12-04",
        "comment_count": 13,
        "like_count": 437,
        "id": "10155952xxxxx"
    },
    {
        "text": "grapes",
        "created_time": "2017-12-04",
        "comment_count": 12,
        "like_count": 163,
        "id": "1015595299xxxxx"
    }
    ]
}

我的电流输出:

"text: grapes"

但是,我想遍历每个字典,最终只打印每个“文本”键的值。

预期产量:

"text: apple"
"text: orange"
"text: grapes"

任何提示都有帮助!谢谢!


Tags: 文件keytextinjson字典timeas