簡體   English   中英

Python:將json列表結果寫入JSON文件

[英]Python: write json list result into JSON file

所以我收到了這種數據:

[{
    'Status': 0,
    'Button': False,
    'Message': None,
    'Id': None,
    'hu': 0,
    'Mode': 'LocModePresence',
    'mac': '00011171815E',
    'mapId': '17_1_0',
    'Seq': 236,
    'tam': False,
    'temperature': 0.0,
    'time': 1603797352911,
    'type': 'TTT',
    'x': 2716.0,
    'y': 648.0,
    'zone': '301990146'
}, {
    'Status': 0,
    'Button': False,
    'Message': '6e0002000c00',
    'Id': '3_2',
    'hu': 0,
    'Mode': 'LocModePresence',
    'mac': '00011171815E',
    'mapId': '17_1_0',
    'Seq': 237,
    'tam': False,
    'temperature': 0.0,
    'time': 1603797357105,
    'type': 'TTT',
    'x': 2716.0,
    'y': 648.0,
    'zone': '301990146'
}]

我想把它寫入JSON文件:

with open('data.json', 'w', encoding='utf-8') as f:
    json.dump(my_data, f, ensure_ascii=False, indent=4)

如果我想把這個數據作為字符串(出於調試原因),為什么當我把它放在 2 '中時,這個符號會顯示error

illegal target for variable annotation

我希望能夠將其寫入我的磁盤並讀取它以與我將獲得的另一個文件進行比較(並且該文件也需要寫入磁盤)

當您從文件中讀取時,您應該使用read()

read() readline()readline()之間的區別記錄在此處:

我什么時候應該使用 file.read() 或 file.readlines()?

import json

my_data = [
    {
        'Status': 0,
        'Button': False,
        'Message': None,
        'Id': None,
        'hu': 0,
        'Mode': 'LocModePresence',
        'mac': '00011171815E',
        'mapId': '17_1_0',
        'Seq': 236,
        'tam': False,
        'temperature': 0.0,
        'time': 1603797352911,
        'type': 'TTT',
        'x': 2716.0,
        'y': 648.0,
        'zone': '301990146',
    },
    {
        'Status': 0,
        'Button': False,
        'Message': '6e0002000c00',
        'Id': '3_2',
        'hu': 0,
        'Mode': 'LocModePresence',
        'mac': '00011171815E',
        'mapId': '17_1_0',
        'Seq': 237,
        'tam': False,
        'temperature': 0.0,
        'time': 1603797357105,
        'type': 'TTT',
        'x': 2716.0,
        'y': 648.0,
        'zone': '301990146',
    },
]


if __name__ == '__main__':
    with open('data.json', 'w', encoding='utf-8') as _file:
        json.dump(my_data, _file, ensure_ascii=False, indent=4)

    with open('data.json', 'r', encoding='utf-8') as _file:
        str_content = _file.read()

    print(type(str_content))
    json_content = json.loads(str_content)
    print(type(json_content))

暫無
暫無

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

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