在python中自动生成有效的json字符串

时间:2018-05-29 07:17:01

标签: python json

我试图在python中动态创建一个json字符串。到目前为止,我有这个testcase_ids是一个唯一数字列表。

    for x in testcase_ids:
        result_details = '{"case_id": ' + str(x) + ',"status_id": 1,"version":"1.0","comment":"Test"}'
        results.append(result_details)
    result_list = ','.join(results)
    json_string = json.dumps(result_list)
    data = {"results": [ json_string ]}

    print (json.dumps(data, indent=4, sort_keys=True))

然而json.dumps的输出是一个长字符串..

{
    "results": ["\"{\\\"case_id\\\": 76565,\\\"status_id\\\": 1,\\\"version\\\":\\\"1.0\\\",\\\"comment\\\":\\\"Test\\\"},
    {\\\"case_id\\\": 76601,\\\"status_id\\\": 1,\\\"version\\\":\\\"1.0\\\",\\\"comment\\\":\\\"Test\\\"},
    {\\\"case_id\\\": 76668,\\\"status_id\\\": 1,\\\"version\\\":\\\"1.0\\\",\\\"comment\\\":\\\"Test\\\"},
    {\\\"case_id\\\": 76731,\\\"status_id\\\": 1,\\\"version\\\":\\\"1.0\\\",\\\"comment\\\":\\\"Test\\\"},
    {\\\"case_id\\\": 76737,\\\"status_id\\\": 1,\\\"version\\\":\\\"1.0\\\",\\\"comment\\\":\\\"Test\\\"},
    {\\\"case_id\\\": 23467,\\\"status_id\\\": 1,\\\"version\\\":\\\"1.0\\\",\\\"comment\\\":\\\"Test\\\"}\""
    ]
}

我最终想要达到的目的是:

data3 = {'results': [{"case_id": 76565,"status_id": 1,"version":"1.0","comment":"Test"},
                         {"case_id": 76601,"status_id": 1,"version":"1.0","comment":"Test"},
                         {"case_id": 76668,"status_id": 1,"version":"1.0","comment":"Test"},
                         {"case_id": 23467,"status_id": 1,"version":"1.0","comment":"Test"}]},

打印时看起来像这样......

[
    {
        "results": [
            {
                "case_id": 76565,
                "comment": "Test",
                "status_id": 1,
                "version": "1.0"
            },
            {
                "case_id": 76601,
                "comment": "Test",
                "status_id": 1,
                "version": "1.0"
            },
            {
                "case_id": 76668,
                "comment": "Test",
                "status_id": 1,
                "version": "1.0"
            },
        ]
    }
]

我也尝试了这个,但是在json.dumps之后添加了json.loads之前它仍然失败了。这将字符串转换为有效的json字符串。固定!

    for x in mrc_testcase_ids:
        result_details = {"case_id": str(x),"status_id": 1,"version":"1.0","comment":"Test"}
        results.append(result_details)
    json_string = json.dumps([{'results': results}])
    valid_json_string = json.loads(json_string)
    print (json.dumps(valid_json_string, indent=4, sort_keys=True))

1 个答案:

答案 0 :(得分:1)

试试这个。希望它能奏效。

for x in testcase_ids:
    result_details = {"case_id": "" + str(x) + "","status_id": 1,"version":"1.0","comment":"Test"}
    results.append(result_details)
json_string = json.dumps(result_list)