将此python字典转换为JSON格式?

时间:2013-06-18 11:06:00

标签: python json

我有一个python字典,我想将其转换为json。

Python词典:

{"20090209.02s1.1_sequence.txt": [645045714, 3559.6422951221466, 206045184], "20090209.02s1.2_sequence.txt": [645045714, 3543.8322949409485, 234618880]}

期望的输出:

{
       "file_name":"20090209.02s1.1_sequence.txt",
       "file_information": [645045714, 3559.6422951221466, 206045184],

    {
       "file_name":"20090209.02s1.2_sequence.txt",
       "file_information": [645045714, 3543.8322949409485, 234618880],

    }
}

尝试json.dumps,但我没有得到所需的输出。

2 个答案:

答案 0 :(得分:7)

您需要先创建一个格式正确的结构:

import json

dict_ = {"20090209.02s1.1_sequence.txt": [645045714, 3559.6422951221466, 206045184], "20090209.02s1.2_sequence.txt": [645045714, 3543.8322949409485, 234618880]}
values = [{"file_name": k, "file_information": v} for k, v in dict_.items()]
json.dumps(values, indent=4)

请注意,所需的JSON输出对我来说看起来不合适。这是此代码的输出:

[
    {
        "file_name": "20090209.02s1.1_sequence.txt", 
        "file_information": [
            645045714, 
            3559.6422951221466, 
            206045184
        ]
    }, 
    {
        "file_name": "20090209.02s1.2_sequence.txt", 
        "file_information": [
            645045714, 
            3543.8322949409485, 
            234618880
        ]
    }
]

答案 1 :(得分:1)

将您的键值对拆分为单独的词典:

json.dumps([{'file_name': key, 'file_information': value} for key, value in yourdict.iteritems()])

请注意,输出的顺序将是任意的(字典没有固定的顺序)。您可能希望对输出进行排序以生成可预测的列表:

from operator import itemgetter

data = [{'file_name': key, 'file_information': value} for key, value in yourdict.iteritems()]
data.sort(key=itemgetter('file_name'))
json.dumps(data)

这会产生:

>>> data = [{'file_name': key, 'file_information': value} for key, value in yourdict.iteritems()]
>>> data.sort(key=itemgetter('file_name'))
>>> json.dumps(data)
'[{"file_name": "20090209.02s1.1_sequence.txt", "file_information": [645045714, 3559.6422951221466, 206045184]}, {"file_name": "20090209.02s1.2_sequence.txt", "file_information": [645045714, 3543.8322949409485, 234618880]}]'
>>> print json.dumps(data, indent=4)

[
    {
        "file_name": "20090209.02s1.1_sequence.txt",
        "file_information": [
            645045714,
            3559.6422951221466,
            206045184
        ]
    },
    {
        "file_name": "20090209.02s1.2_sequence.txt",
        "file_information": [
            645045714,
            3543.8322949409485,
            234618880
        ]
    }
]