1

I am trying to make a list of JSON objects in python I have an list of keys, and a list of items, so keys is something like this, by the way I am getting this list from the web so it is always a single quote

keys = ['one', 'two', 'three']

and then items something like this

rows = [[foo, fuu, fhh], [bar, bat, bak]]

And what I want is

[{"one":"foo", "two":"fuu", "three":"fhb"},
{"one":"bar", "two":"bat", "three":"bak"}]

And here is what I am trying but I end up with this

['{"one":"foo", "two":"fuu", "three":"fhb"}',
'{"one":"bar", "two":"bat", "three":"bak"}']

Which makes it no longer valid JSON:

results = []
info = {}
for row in items:
    i = 0
    for item in row:
        info[keys[i]] = item
        data = json.dumps(info)
        i += 1
    results.append(data)

So how can I get rid of those single quotes and just have double quotes and valid JSON?

Thanks

spen123
  • 3,464
  • 11
  • 39
  • 52

2 Answers2

1

When you use json.dumps you create a json string that can be written to a file that represents your data. You should create the list and then, at the end, use json.dumps to create your json.

You could also use zip to make your code more readable:

>>> results = [dict(zip(keys, row)) for row in rows]
>>> print results

[{'one': 'foo', 'three': 'fhh', 'two': 'fuu'},
 {'one': 'bar', 'three': 'bak', 'two': 'bat'}]

>>> json.dumps(results)

'[{"three": "fhh", "two": "fuu", "one": "foo"}, {"three": "bak", "two": "bat", "one": "bar"}]'
enrico.bacis
  • 30,497
  • 10
  • 86
  • 115
1

Move the json.dumps at the end, not at each iteration:

results = []
for row in items:
    i = 0
    info = {}
    for item in row:
        info[keys[i]] = item
        i += 1
    results.append(info)

return json.dumps(results)

It will first construct your list of strings and then serialize the Python object as a JSON one.

Maxime Lorant
  • 34,607
  • 19
  • 87
  • 97
  • okay now that I have after the `json.dumps` I get this `final_result =[{"one":"foo", "two":"fuu", "three":"fhb"}, {"one":"bar", "two":"bat", "three":"bak"}]` how could I just get the first JSON because final_result[0] doesn't work? – spen123 Aug 05 '15 at 19:29
  • 1
    I don't understand what you want then. Why do you want a JSON object if it is for accessing items after via Python syntax? `results` is a Python object: you can do `results[0]['one']` (which returns foo). With `json.dump(results)` you get a JSON representation of the list of dict. You need to do `json.loads` before to be able to use it as a Python object again. – Maxime Lorant Aug 05 '15 at 19:32
  • @spenf10 Agree with Maxime. If you're going to try to use the data when you're done, you don't want JSON. You just want the `list` of `dict`s without converting to JSON. JSON is strictly text data, usually used for exchanging data between two different systems (like between a web application and a browser). – jpmc26 Aug 05 '15 at 21:33