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

我有一个要转换成json的python字典。


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但是我没有得到想要的输出。


繁花不似锦
浏览 183回答 3
3回答

慕斯709654

您需要首先创建具有正确格式的结构:import jsondict_ = {"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        ]    }]

慕后森

将键值对拆分为单独的字典:json.dumps([{'file_name': key, 'file_information': value} for key, value in yourdict.iteritems()])请注意,输出的顺序将是任意的(字典没有固定的顺序)。您可能需要对输出进行排序以生成可预测的列表:from operator import itemgetterdata = [{'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        ]    }]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python