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

5

11

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?

Bronk answered 7/12, 2012 at 10:16 Comment(0)
W
31

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"}
Whiggism answered 7/12, 2012 at 10:19 Comment(10)
('datetime.datetime(2012, 12, 7, 10, 53, 22) is not JSON serializable',) - does this mean all my values have to be strings? (and if they do, is there a nice way to make that happen?)Bronk
@cskilbeck: yes, datetime objects have no default serialization to JSON. You need to turn those into strings manually.Whiggism
@cskilbeck: See JSON datetime between Python and JavaScriptWhiggism
the original input list may have multiple tuples with the same first element. if this is converted to dictionary they will be overwrittenKernel
@mustafa: a JSON Object keys should be unique, however. In that case you would be much better off outputting a list of 2-element lists.Whiggism
@mustafa: But if you must have a JSON Object with duplicate keys, then use '{{{}}}'.format(','.join(['{}:{}'.format(json.dumps(k), json.dumps(v)) for k, v in lst])) to at least format the keys and values with the json module (or f"{{{','.join([f'{json.dumps(k)}:{json.dumps(v)}' for k, v in lst])}}}" when using Python 3.6 or up). Take into account that whomever consumes this output must also explicitly support duplicate keys.Whiggism
this answer works only for 2 items per tuple, what about n items in tuple ?Melpomene
@danibilel how would you expect an n-item tuple to be represented then? The OP had names and values so this naturally translates to a JSON object; if you have a different structure a different transformation is needed altogether.Whiggism
well i have a list of 5-tuples that i've been trying to serialize by transforming it to a json but it just won't ! i made it a dictionary of 5 items, didn't work, i tried to structure the data in a class, that didn't work also, i tried to transform one object at a time, no luck, i might ask a question if i don't find a solution to this.Melpomene
@danibilel: then just transform those tuples to lists. You don't have key-value pairs, you have specific sequences.Whiggism
S
1
(lambda lst: json.dumps({item[0]:item[1] for item in lst}))([(1,2), (3,4)])
Sago answered 7/12, 2012 at 10:25 Comment(2)
if you love lambdas, i dooSago
{item[0]:item[1] for item in lst} == dict(lst)Parallelism
S
0

You can convert it to one complete JSON content:

import ast
import json

stli = '[(\'Rated 4.0\', \'RATED\\n  A beautiful place to dine in.The interiors take you back to the Mughal era. The lightings are just perfect.We went there on the occasion of Christmas and so they had only limited items available. But the taste and service was not compromised at all.The only complaint is that the breads could have been better.Would surely like to come here again.\'), (\'Rated 4.0\', \'RATED\\n  I was here for dinner with my family on a weekday. The restaurant was completely empty. Ambience is good with some good old hindi music. Seating arrangement are good too. We ordered masala papad, panner and baby corn starters, lemon and corrionder soup, butter roti, olive and chilli paratha. Food was fresh and good, service is good too. Good for family hangout.\\nCheers\'), (\'Rated 2.0\', \'RATED\\n  Its a restaurant near to Banashankari BDA. Me along with few of my office friends visited to have buffet but unfortunately they only provide veg buffet. On inquiring they said this place is mostly visited by vegetarians. Anyways we ordered ala carte items which took ages to come. Food was ok ok. Definitely not visiting anymore.\'), (\'Rated 4.0\', \'RATED\\n  We went here on a weekend and one of us had the buffet while two of us took Ala Carte. Firstly the ambience and service of this place is great! The buffet had a lot of items and the good was good. We had a Pumpkin Halwa intm the dessert which was amazing. Must try! The kulchas are great here. Cheers!\'), (\'Rated 5.0\', \'RATED\\n  The best thing about the place is itÃ\x83Â\x82Ã\x82Â\x92s ambiance. Second best thing was yummy ? food. We try buffet and buffet food was not disappointed us.\\nTest ?. ?? ?? ?? ?? ??\\nQuality ?. ??????????.\\nService: Staff was very professional and friendly.\\n\\nOverall experience was excellent.\\n\\nsubirmajumder85.wixsite.com\'), (\'Rated 5.0\', \'RATED\\n  Great food and pleasant ambience. Expensive but Coll place to chill and relax......\\n\\nService is really very very good and friendly staff...\\n\\nFood : 5/5\\nService : 5/5\\nAmbience :5/5\\nOverall :5/5\'), (\'Rated 4.0\', \'RATED\\n  Good ambience with tasty food.\\nCheese chilli paratha with Bhutta palak methi curry is a good combo.\\nLemon Chicken in the starters is a must try item.\\nEgg fried rice was also quite tasty.\\nIn the mocktails, recommend "Alice in Junoon". Do not miss it.\'), (\'Rated 4.0\', \'RATED\\n  You canÃ\x83Â\x82Ã\x82Â\x92t go wrong with Jalsa. Never been a fan of their buffet and thus always order alacarteÃ\x83Â\x82Ã\x82Â\x92. Service at times can be on the slower side but food is worth the wait.\'), (\'Rated 5.0\', \'RATED\\n  Overdelighted by the service and food provided at this place. A royal and ethnic atmosphere builds a strong essence of being in India and also the quality and taste of food is truly authentic. I would totally recommend to visit this place once.\'), (\'Rated 4.0\', \'RATED\\n  The place is nice and comfortable. Food wise all jalea outlets maintain a good standard. The soya chaap was a standout dish. Clearly one of trademark dish as per me and a must try.\\n\\nThe only concern is the parking. It very congested and limited to just 5cars. The basement parking is very steep and makes it cumbersome\'), (\'Rated 4.0\', \'RATED\\n  The place is nice and comfortable. Food wise all jalea outlets maintain a good standard. The soya chaap was a standout dish. Clearly one of trademark dish as per me and a must try.\\n\\nThe only concern is the parking. It very congested and limited to just 5cars. The basement parking is very steep and makes it cumbersome\'), (\'Rated 4.0\', \'RATED\\n  The place is nice and comfortable. Food wise all jalea outlets maintain a good standard. The soya chaap was a standout dish. Clearly one of trademark dish as per me and a must try.\\n\\nThe only concern is the parking. It very congested and limited to just 5cars. The basement parking is very steep and makes it cumbersome\')]'

inputlist = list(ast.literal_eval(stli))

rs = json.dumps(dict(inputlist))

print(rs)

Output:

{"Rated 4.0": "RATED\n  The place is nice and comfortable. Food wise all jalea outlets maintain a good standard. The soya chaap was a standout dish. Clearly one of trademark dish as per me and a must try.\n\nThe only concern is the parking. It very congested and limited to just 5cars. The basement parking is very steep and makes it cumbersome", "Rated 2.0": "RATED\n  Its a restaurant near to Banashankari BDA. Me along with few of my office friends visited to have buffet but unfortunately they only provide veg buffet. On inquiring they said this place is mostly visited by vegetarians. Anyways we ordered ala carte items which took ages to come. Food was ok ok. Definitely not visiting anymore.", "Rated 5.0": "RATED\n  Overdelighted by the service and food provided at this place. A royal and ethnic atmosphere builds a strong essence of being in India and also the quality and taste of food is truly authentic. I would totally recommend to visit this place once."}
Selfdeceit answered 30/3, 2019 at 5:35 Comment(0)
Y
0

I think this is a much simple solution. Courtesy w3 schools https://www.w3schools.com/python/python_json.asp

import json

some JSON:

x =  '{ "name":"John", "age":30, "city":"New York"}'

parse x:

y = json.loads(x)

the result is a Python dictionary:

print(y["age"])
Yellowstone answered 19/5, 2020 at 4:30 Comment(1)
Thanks Karan, w3schools is awesome for sure, although this parses some JSON rather than formatting a dictionary for output.Bronk
N
0

You can create a dictionary that looks something like:

all_lst = []
for nm, val in lst:
    if val != None:
        lst_dict = {}
        lst_dict[nm] = val
        all_lst.append(lst_dict)
return jsonify(all_lst)
Nonmaterial answered 14/8, 2023 at 17:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.