从元组列表格式化JSON字符串的更具Python风格的方法

从元组列表格式化JSON字符串的更具Python风格的方法,python,json,list,tuples,Python,Json,List,Tuples,目前我正在这样做: def getJSONString(lst): join = "" rs = "{" for i in lst: rs += join + '"' + str(i[0]) + '":"' + str(i[1]) + '"' join = "," return rs + "}" 我称之为: rs = getJSONString([("name", "value"), ("name2", "value2")])

目前我正在这样做:

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

rs = getJSONString([("name", "value"), ("name2", "value2")])
它不需要嵌套(它只是一个简单的名称-值对列表)。但我愿意以不同的方式调用函数。这一切似乎有点笨拙,有没有更优雅的方式?这需要在2.x下运行

请注意,这不是的重复:(除非可以修改该答案以创建JSON字符串作为输出)


编辑:将名称-值对作为字典传递会更好吗?

有一种更好的生成JSON字符串的方法:

这充分利用了
dict()
可以获取一系列键值对(两个值元组)并将其转换为映射的事实,
json
模块直接将其转换为json对象结构

演示:

>>> import json
>>> lst = [("name", "value"), ("name2", "value2")]
>>> rs = json.dumps(dict(lst))
>>> print rs
{"name2": "value2", "name": "value"}

您可以在中转换为一个完整的json内容

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)
输出:
{“Rated 4.0”:“Rated\n这个地方很好,也很舒适。所有jalea门店的食品质量都很好。大豆沙拉是一道很突出的菜。很明显,我认为这是一道招牌菜,必须试一试。\n\n唯一关心的是停车位。停车位非常拥挤,仅限5辆车。地下室停车位非常陡峭,很麻烦”,“额定值2.0”:RATED\n这是一家靠近Banashankari BDA的餐厅。我和我的几个办公室朋友来过这里吃自助餐,但不幸的是他们只提供蔬菜自助餐。询问时他们说这个地方大部分是素食者来的。不管怎样,我们点的是点菜,这需要很长时间。食物还可以。绝对不再来了。“”评级为5.0:“这个地方提供的服务和食物给我的评级太高了。皇家和民族氛围营造了强烈的印度精神,而且食物的质量和味道都是真实的。我完全建议你去这个地方一次。”}

我认为这是一个非常简单的解决方案。由w3学校提供

一些JSON:

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

y = json.loads(x)
结果是一个Python字典:

print(y["age"])

如果你喜欢lambdas,我会告诉你,
{item[0]:item[1]for item in lst}==dict(lst)
('datetime.datetime(2012,12,7,10,53,22)不是JSON可序列化的')-这是否意味着我所有的值都必须是字符串?(如果是,有没有一个好的方法实现这一点?)@Cskibeck:是的,
datetime
对象没有默认的JSON序列化。您需要手动将它们转换为字符串。@Cskibeck:请参阅原始输入列表中可能有多个元组,它们的第一个元素相同。如果将其转换为字典,它们将被删除overwritten@mustafa:但如果您必须具有具有重复键的JSON对象,然后使用
{{}}.format(“,”.join([{}:{}.format(json.dumps(k),json.dumps(v))代表k,v在lst中])
至少用
json
模块格式化键和值(或
f{{},”.join([f'{json.dumps(k)}:{json.dumps(v)}代表k,v在lst中),在使用Python 3.6或up时,
。请注意,使用此输出的用户也必须明确支持重复键。感谢Karan,w3schools确实很棒,尽管它解析了一些JSON,而不是格式化输出的字典。
x =  '{ "name":"John", "age":30, "city":"New York"}'
y = json.loads(x)
print(y["age"])