簡體   English   中英

Python:將JSON字典值寫入JSON文件

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

我試圖:

  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"

任何提示都會有所幫助! 謝謝!

你已經打開的文件w模式,你需要把它開成a (追加模式)

來自docs

1.'w'僅用於寫入(將擦除具有相同名稱的現有文件)

2.'a'打開附加文件; 寫入文件的任何數據都會自動添加到最后

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

comments.json內容,

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

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)

如果我確實理解你,這應該做你想要的:

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

只要改變“W”到“A”,所以你不要過度W¯¯儀式,但一個 PPEND到文件

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM