如何将dicts插入JSON数组文件?

时间:2016-12-10 00:42:34

标签: python arrays json list dictionary

我编写了一个小的Python脚本,它利用speedtest-cli来提高我的网速。我打算创建一个装置,我的Python脚本将速度数据存储在磁盘上已存在的JSON数组文件中,然后设置一个小网页来查看数据。

无论如何,我已经配置了我的脚本,它在脚本末尾吐出dict,如下所示:

{
    "downSpeed": 90.30834444821808,
    "humanTime": "Fri Dec  9 18:02:54 2016",
    "time": 1481328174225.999,
    "upSpeed": 13.698571043448549
}

我在磁盘上有一个JSON文件,它只是一个带有两个括号的文件来表示JSON数组,在该数组中,我希望我的脚本将dicts放在JSON数组中,用逗号分隔在JSON中将dicts表示为objects。我的问题是如何将数据输入JSON文件?我遇到的所有解决方案都提到使用open功能和a选项。但是,这有几个问题,首先,数据被附加到文件,JSON的最后一个括号因为数据被追加而被切断。其次,由于我计划经常运行这个脚本,我担心我会遇到JSON文件很长的问题,因此需要很长时间才能处理脚本。那么,我的选择是什么?是否有另一种方法可以将dict插入到JSON数组中(我想在Python中松散地转换为list)?

4 个答案:

答案 0 :(得分:0)

你熟悉python JSON模块吗? https://docs.python.org/2/library/json.html 您可以使用dumps()将python对象直接写入JSON文件。 网站示例:

    import json
    print json.dumps({'4': 5, '6': 7}, sort_keys=True,
                      indent=4, separators=(',', ': '))

    {
        "4": 5,
        "6": 7

    }

答案 1 :(得分:0)

通常,没有简单的方法可以在文件中间插入内容。因此,您必须解析所有JSON以在内存中创建列表,附加项目,然后再次转储它。或者你可以用逗号和方括号来手动操作JSON数组。

在这种情况下,更好的选择是忘记JSON数组并将每个JSON对象存储在一行中。这样,您可以使用追加模式,也可以轻松遍历对象,而无需将整个文件加载到内存中。

答案 2 :(得分:0)

如果您想将JSON代码附加到现有的JSON文件(.json),那么您需要使用的只是Python的json模块。假设您有一个名为test.json的文件,其中包含代码

[ "Hello World!", "Testing 1, 2, 3." ]

然后,您要将以下Python字典附加到列表中。

{ "Hello World!": 123, "Test": None }

python代码看起来像这样。

import json # import the module

code = json.load(open('test.json','r')) # load the current data
adding_dict = # put the python dictionary here,
              # it can even be a class if it returns a dictionary.
new_dict = code.append(adding_dict) # append the dictionary to the list
# then we dump it to the file.
json.dump(new_dict, open('test.json', 'w'))

如果您想了解更多信息,请参阅Python的文档网站here.

答案 3 :(得分:0)

import jsonlines

net_speed = {
               "downSpeed": 90.30834444821808,
               "humanTime": "Fri Dec  9 18:02:54 2016",
               "time": 1481328174225.999,
               "upSpeed": 13.698571043448549
            }

# net.jsonl is the name of the file
with jsonlines.open("net.jsonl", "a") as writer:   # for writing
    writer.write(net_speed)

with jsonlines.open('net.jsonl') as reader:      # for reading
    for obj in reader:
        print(obj)             

访问以了解更多信息https://jsonlines.readthedocs.io/en/latest/