繁体   English   中英

如何使用python创建有效的json文件?

[英]how to create a valid json file using python?

使用python创建一个json文件,它将具有多个条目,如下所示:

    out=''
    with open('data.json', 'w') as outfile:
        i=0;

        for i in range(3):
             string = "test_"+str(i)+'"'+':{ "status": "false", "test_id": 123453},'
             out= out+string.replace("\\","");
             i=i+1;      
        json.dump("{"+out+"}", outfile)

该文件输出为:

 "{test_0\":{ \"status\": \"false\", \"test_id\": 123453},test_1\":{ \"status\": \"false\", \"test_id\": 123453},test_2\":{ \"status\": \"false\", \"test_id\": 123453},}"

但理想情况下,正确的输出应为:

 {
 "test_0":
    {
     "status": "false", 
    "test_id": 123453
    },
  "test_1":
    { 
     "status": "false",
     "test_id": 123453
    },
  "test_2":
    { 
      "status": "false",
     "test_id": 123453
    }
}

因此,即将出现的输出具有“ \\”,我如何将它们全部删除。 它总是出现在文件中,也尝试过使用条带但不值得。 救命!!

您是否尝试重新制作json.dump? 通常,json.dump可以完成该工作。

import json
import sys

out = {}
i = 0

for i in range(3):
    out["test_"+str(i)] = { "status": "false", "test_id": 123453 }
    i = i + 1

json.dump(out, sys.stdout, indent = 4)

构建中的json模块可将pyhton数据结构转储到合适的json代码中。

您为它提供了一个字符串-并将其转储为正确的字符串。 它通过将每个内部"放置为\\"掩盖每个内部文件,以便当您读取文件并对其进行json.load()时,它将重新创建您提供的确切python字符串。

底线:不要构建数据字符串,构建数据并让json完成其工作:

import json
d =  {'test_0': {'status': 'false', 'test_id': 123453}, 
      'test_1': {'status': 'false', 'test_id': 123453}, 
      'test_2': {'status': 'false', 'test_id': 123453}}

with open('data.json', 'w') as outfile:
    json.dump(d,outfile, indent=4)   # use indent to pretty print


with open('data.json', 'r') as outfile:
    print("")
    print(outfile.read())

输出:

{
    "test_0": {
        "status": "false",
        "test_id": 123453
    },
    "test_1": {
        "status": "false",
        "test_id": 123453
    },
    "test_2": {
        "status": "false",
        "test_id": 123453
    }
}

Doku: https ://docs.python.org/3/library/json.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM