簡體   English   中英

將 json 數據附加到 json 文件

[英]Appending json data to json file

我有以下代碼檢查 json 文件是否存在,如果存在,則我將新的 json 數據添加到文件中,但如果不存在,則創建新文件 json 文件。

def createJsonHashtag(hashtag, post):
    f = "hashtag.json"
    x = {hashtag:post}
    if os.path.exists(f):
        with open(f, "r+") as file:
            data = json.load(file)
            data.update(x)
            file.seek(0)
            json.dump(data, file)
    else:
        # parse x as json
        y = json.dumps(x)
        open(f,'w').write(y)

在上述代碼中,hashtag 和 post 變量的內容如下。

hashtag = "#movie"
post = {'PostHashHex': '114fb796599f0b55dae2fdef3d81850ad7eedc45f11b6eec70262c001e11ceae', 'PosterPublicKeyBase58Check': 'BC1YLhKJZZcPB2WbZSSekFF19UshsmmPoEjtEqrYakzusLmL25xxAJv', 'ParentStakeID': '', 'Body': \"Which movies are ur favorite from tonight's Oscars'?\\n\\n#movies #oscars\"}

但是當我運行代碼時,出現以下錯誤:

File "hashtag-analyzer.py", line X, in createJsonHashtag
    data = json.load(file)   File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/__init__.py",
line 299, in load
    parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)   File
"/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/__init__.py",
line 354, in loads
    return _default_decoder.decode(s)   File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/decoder.py",
line 342, in decode
    raise JSONDecodeError("Extra data", s, end)

為什么會發生這種情況以及如何解決?

抱歉, post變量的內容包含非法的\字符。

post = {
    'PostHashHex': '114fb796599f0b55dae2fdef3d81850ad7eedc45f11b6eec70262c001e11ceae',
    'PosterPublicKeyBase58Check': 'BC1YLhKJZZcPB2WbZSSekFF19UshsmmPoEjtEqrYakzusLmL25xxAJv',
    'ParentStakeID': '',
    'Body': \"Which movies are ur favorite from tonight's Oscars'?\\n\\n#movies #oscars\"
}

您的代碼根本無法在 PyCharm 中運行,因為body鍵值在雙引號之前有一個\

暫無
暫無

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

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