13

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)

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"}]

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.

Bob Jordan
  • 3,049
  • 2
  • 34
  • 41

3 Answers3

31

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])
jfs
  • 399,953
  • 195
  • 994
  • 1,670
  • can we do a reverse of this ? converting a string which is array of json objects to dict ? – divyenduz Nov 11 '14 at 13:37
  • 1
    @divyenduz: the "reverse of this" is converting a json text that contains an array of json objects into *list* of dictionaries. Yes, we can: `list_of_dicts = json.loads(json_text)`. If something is unclear, [ask](http://stackoverflow.com/questions/ask) – jfs Dec 01 '14 at 16:52
11

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"}]
o12d10
  • 800
  • 3
  • 17
  • 31
Xavier Combelle
  • 10,968
  • 5
  • 28
  • 52
  • Doh, thank you very much for the solution that match my original (inelegant) code. The one line solution is obviously better code but I appreciate you revealing my error. – Bob Jordan Jul 03 '12 at 14:34
0
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
4b0
  • 21,981
  • 30
  • 95
  • 142