简体   繁体   English

Python:将 Python 字典列表转换为 JSON 对象数组

[英]Python: Convert a list of python dictionaries to an array of JSON objects

I'm trying to write a function to convert a python list into a JSON array of {"mpn":"list_value"} objects, where "mpn" is the literal string value I need for every object but "list_value" is the value from the python list.我正在尝试编写一个函数来将 python 列表转换为 {"mpn":"list_value"} 对象的 JSON 数组,其中 "mpn" 是每个对象所需的文字字符串值,但 "list_value" 是该值来自蟒蛇列表。 I'll use the output of this function for an API get request.我会将此函数的输出用于 API 获取请求。

part_nums = ['ECA-1EHG102','CL05B103KB5NNNC','CC0402KRX5R8BB104']

def json_list(list):
    lst = []
    d = {}
    for pn in list:
        d['mpn']=pn
        lst.append(d)
    return json.dumps(lst, separators=(',',':'))

print json_list(part_nums)

This current function is not working and returns last value in the python list for all JSON objects:此当前函数不起作用并返回所有 JSON 对象的 python 列表中的最后一个值:

>[{"mpn":"CC0402KRX5R8BB104"},{"mpn":"CC0402KRX5R8BB104"},{"mpn":"CC0402KRX5R8BB104"}]

However, of course I need my function to return the unique list values in the objects as such:但是,当然我需要我的函数来返回对象中的唯一列表值,如下所示:

>[{"mpn":"ECA-1EHG102"},{"mpn":"CL05B103KB5NNNC"},{"mpn":"CC0402KRX5R8BB104"}]

Bottom line is I don't understand why this function isn't working.底线是我不明白为什么这个功能不起作用。 I expected I could append a dictionary with a single {key:value} pair to a python list and it wouldn't matter that all of the dictionaries have the same key because they would be independent.我希望我可以将带有单个 {key:value} 对的字典附加到 python 列表中,并且所有字典都具有相同的键并不重要,因为它们是独立的。 Thanks for your help.谢谢你的帮助。

You are adding the exact same dictionary to the list.您正在将完全相同的字典添加到列表中。 You should create a new dictionary for each item in the list:您应该为列表中的每个项目创建一个新字典:

json.dumps([dict(mpn=pn) for pn in lst])

As explained by others (in answers) you should create a new dictionary for each item on the list elsewhere you reference always the same dictionary正如其他人(在答案中)所解释的那样,您应该为列表中的每个项目创建一个新字典,而您在其他地方始终引用相同的字典

import json
part_nums = ['ECA-1EHG102','CL05B103KB5NNNC','CC0402KRX5R8BB104']

def json_list(list):
    lst = []
    for pn in list:
        d = {}
        d['mpn']=pn
        lst.append(d)
    return json.dumps(lst)

print json_list(part_nums)

print打印

[{"mpn": "ECA-1EHG102"}, {"mpn": "CL05B103KB5NNNC"}, {"mpn": "CC0402KRX5R8BB104"}]
import json
part_nums = ['ECA-1EHG102','CL05B103KB5NNNC','CC0402KRX5R8BB104']

def json_list(list):
    lst = []
    for pn in list:
        d = {}
        d['mpn']=pn
        lst.append(d)
    return json.dumps(lst)

print json_list(part_nums)   # for pyhon2
print (json_list(part_nums)) # for python3

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

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