【问题标题】:Python: write json list result into JSON filePython:将json列表结果写入JSON文件
【发布时间】:2020-10-27 11:52:51
【问题描述】:

所以我收到了这种数据:

[{
    '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

我希望能够将其写入我的磁盘并读取它以与我将获得的另一个文件进行比较(并且此文件需要写入磁盘上)

【问题讨论】:

  • 所以我不清楚问题是什么,我复制粘贴了您的代码,并且能够成功将其保存为文件,

标签: python json


【解决方案1】:

当你从文件中读取时,你应该使用read()

read() readline()readline() 之间的区别记录在这里:

When should I ever use file.read() or 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))

【讨论】:

  • 好的,但是当我尝试加载这个保存的文件(json.loads)时,我遇到了这个错误:从无 json.decoder 引发 JSONDecodeError("Expecting value", s, err.value)。 JSONDecodeError:预期值:第 1 行第 1 列(字符 0)
  • 使用json.dumps 的想法是将结果存储在变量中,正如我在 cmets 中解释的那样,并且能够使用该变量(包括将其写入文件)。你也应该使用write(),而不是writelines()
  • 以你的例子为例:在我的磁盘上有这个文件和另一个文件之后,我如何比较它们?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-24
  • 1970-01-01
  • 2017-07-31
  • 2020-07-18
  • 1970-01-01
  • 2017-12-28
相关资源
最近更新 更多