Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

more pythonic way to format a JSON string from a list of tuples

Currently I'm doing this:

def getJSONString(lst):
    join = ""
    rs = "{"
    for i in lst:
        rs += join + '"' + str(i[0]) + '":"' + str(i[1]) + '"'
        join = ","
    return rs + "}"

which I call like:

rs = getJSONString([("name", "value"), ("name2", "value2")])

It doesn't need to be nested (it's only ever going to be a simple list of name value pairs). But I am open to calling the function differently. It all seems a bit cludgy, is there a more elegant way? This needs to run under 2.x.

Note that this is not a duplicate of: Python - convert list of tuples to string (unless that answer can be modified to create a JSON string as output).

edit: would it be better to pass the name value pairs as a dictionary?

like image 379
Charlie Skilbeck Avatar asked Dec 07 '12 10:12

Charlie Skilbeck


1 Answers

There is a much better way to generate JSON strings: the json module.

import json
rs = json.dumps(dict(lst))

This takes advantage of the fact that dict() can take a sequence of key-value pairs (two-value tuples) and turn that into a mapping, which the json module directly translates to a JSON object structure.

Demonstration:

>>> import json
>>> lst = [("name", "value"), ("name2", "value2")]
>>> rs = json.dumps(dict(lst))
>>> print rs
{"name2": "value2", "name": "value"}
like image 156
Martijn Pieters Avatar answered Oct 20 '22 08:10

Martijn Pieters