简体   繁体   English

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

[英]Python: Write JSON dictionary values to a JSON file

I am attempting to: 我试图:

  1. Load data from a JSON list of dictionaries 从JSON词典列表加载数据
  2. Write the values of a specific key from each dictionary to a file 将每个字典中特定键的值写入文件

Yet, when I attempt to dump the key pairs to the new .json file, it only prints the very last dictionary key pair. 然而,当我尝试将密钥对转储到新的.json文件时,它只打印最后一个字典密钥对。 Anyone know how to loop through each dictionary and append the key pair? 任何人都知道如何遍历每个字典并附加密钥对? I have tried a few methods but I can't seem to figure out what i'm missing and where. 我尝试了一些方法,但我似乎无法弄清楚我错过了什么,在哪里。

Here is my code: 这是我的代码:

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

A sample of my JSON file: 我的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"
    }
    ]
}

My current output: 我目前的输出:

"text: grapes"

But, I want to loop through every dictionary and eventually print only the values from each "text" key. 但是,我想循环遍历每个字典,并最终只打印每个“文本”键的值。

Expected Output: 预期产出:

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

Any hints will help! 任何提示都会有所帮助! Thanks! 谢谢!

You have opened file in w mode, you need to open it into a (append mode) 你已经打开的文件w模式,你需要把它开成a (追加模式)

from docs : 来自docs

1. 'w' for only writing (an existing file with the same name will be erased) 1.'w'仅用于写入(将擦除具有相同名称的现有文件)

2. 'a' opens the file for appending; 2.'a'打开附加文件; any data written to the file is automatically added to the end 写入文件的任何数据都会自动添加到最后

Python 3.6.5 (default, Mar 30 2018, 06:42:10)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> my_list = [{u'created_time': u'2017-12-23', u'text': u'apple', u'comment_count': 154, u'like_count': 856, u'id': u'1015595299xxxxx'}, {u'created_time': u'2017-12-04', u'text': u'orange', u'comment_count': 13, u'like_count': 437, u'id': u'10155952xxxxx'}, {u'created_time': u'2017-12-04', u'text': u'grapes', u'comment_count': 12, u'like_count': 163, u'id': u'1015595299xxxxx'}]
>>> import json
>>> my_list = [{u'created_time': u'2017-12-23', u'text': u'apple', u'comment_count': 154, u'like_count': 856, u'id': u'1015595299xxxxx'}, {u'created_time': u'2017-12-04', u'text': u'orange', u'comment_count': 13, u'like_count': 437, u'id': u'10155952xxxxx'}, {u'created_time': u'2017-12-04', u'text': u'grapes', u'comment_count': 12, u'like_count': 163, u'id': u'1015595299xxxxx'}]
>>> for d in my_list:
...     for key, value in d.items():
...             if key == "text":
...                     with open('comments.json', 'a') as f:  # Append mode here
...                             json.dump("{}: {}".format(key,value), f)
...                             f.write('\n')
...

Contents of comments.json , comments.json内容,

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

File modes in Python, Python中的文件模式,

'r' open for reading (default)
'w' open for writing, truncating the file first
'x' open for exclusive creation, failing if the file already exists
'a' open for writing, appending to the end of the file if it exists
'b' binary mode
't' text mode (default)
'+' open a disk file for updating (reading and writing)
'U' universal newlines mode (deprecated)

If I did understand you correctly, this should do what you want: 如果我确实理解你,这应该做你想要的:

with open('comments.json', 'a') as f:
    json.dump("{}: {}".format(key,value), f)    #write key pair objects as json formatted stream to json file
    f.write('\n')

Just change 'w' to 'a' so you don't over w rite but a ppend to the file 只要改变“W”到“A”,所以你不要过度W¯¯仪式,但一个 PPEND到文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM