使用Python将字典写入JSON

时间:2012-02-07 02:52:51

标签: python json

我是Python编程的新手,所以如果我在任何地方犯错误,请耐心等待

我正在尝试使用2个字典编写一个json文件,并使用Windows上的以下代码将输出转储到该文件

import json
import sys
import string
from time import strftime

scan_results = open("scan_results.txt", "r")
saved = sys.stdout
f = file('report.json', 'wb')
sys.stdout = f
for line in scan_results:
    if ".jpg" in line:
        lst = []
        result = line.split('\\')
        result_split = result[5].split(' ')
        filename = result_split[0]
        raw_status = result_split[3]
        if "OK" in raw_status:
            status = "Okay"
            status_code = "0"
        dict = {'FileName': filename, 'DateTime': strftime("%Y-%m-%d %H:%M:%S"), 'statusCode': status_code, 'Description': status}
        dict2 = {filename : dict}
        print json.dumps(dict2)
sys.stdout = saved
f.close()
print "JSON report written"

问题是,我的输出是

{
    "car-30537.jpg": {
        "statusCode": "0",
        "DateTime": "2012-02-07 09:52:26",
        "Description": "Okay",
        "FileName": "car-30537.jpg"
    }
}{
    "car-30538.jpg": {
        "statusCode": "0",
        "DateTime": "2012-02-07 09:52:26",
        "Description": "Okay",
        "FileName": "car-30538.jpg"
    }
}

而我想要的输出是

{
    "car-30537.jpg": {
        "statusCode": "0",
        "DateTime": "2012-02-07 09:52:26",
        "Description": "Okay",
        "FileName": "car-30537.jpg"
    },
    {
    "car-30538.jpg": {
        "statusCode": "0",
        "DateTime": "2012-02-07 09:52:26",
        "Description": "Okay",
        "FileName": "car-30538.jpg"
    }
}

有没有办法纠正这个问题?提前致谢

1 个答案:

答案 0 :(得分:1)

你正在制作大量的词汇,而你只需要一个包含一个的主词:

import json
import sys
import string
from time import strftime

scan_results = open("scan_results.txt", "r")
saved = sys.stdout
f = file('report.json', 'wb')
sys.stdout = f
dict2 = {} #Create one output dict
for line in scan_results:
    if ".jpg" in line:
        lst = []
        result = line.split('\\')
        result_split = result[5].split(' ')
        filename = result_split[0]
        raw_status = result_split[3]
        if "OK" in raw_status:
            status = "Okay"
            status_code = "0"
        dict2[filename] = {'FileName': filename, 'DateTime': strftime("%Y-%m-%d %H:%M:%S"), 'statusCode': status_code, 'Description': status} #Add to that dict.
print json.dumps(dict2) #Print it out at the end.
sys.stdout = saved
f.close()
print "JSON report written"

我在修改后的行中添加了评论。