Python:将python字典列表转换为JSON对象数组
我正在尝试编写一个将python列表转换为{"mpn":"list_value"}对象的JSON数组的函数,其中"mpn"是我需要除"list_value"之外的每个对象的文字字符串值是python列表中的值.我将将此函数的输出用于API get请求.
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. I'll use the output of this function for an API get request.
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)
此当前函数不起作用,并返回python列表中所有JSON对象的最后一个值:
This current function is not working and returns last value in the python list for all JSON objects:
>[{"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"}]
最重要的是,我不明白为什么此功能无法正常工作.我希望我可以将带有一对{key:value}对的字典附加到python列表中,并且所有字典都具有相同的键并不重要,因为它们将是独立的.感谢您的帮助.
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. 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])