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

前端 未结 3 618
心在旅途
心在旅途 2021-02-03 10:46

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

相关标签:
3条回答
  • 2021-02-03 10:54

    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"}]
    
    0 讨论(0)
  • 2021-02-03 10:59
    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
    
    0 讨论(0)
  • 2021-02-03 11:10

    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])
    
    0 讨论(0)
提交回复
热议问题