从元组列表格式化JSON字符串的更多pythonic方法 [英] more pythonic way to format a JSON string from a list of 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")])
它不需要嵌套(它只会是一个简单的名称/值对列表).但是我愿意以不同的方式调用该函数.似乎有点笨拙,有没有更优雅的方式?这需要在2.x下运行.
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.
请注意,这不是以下项的重复项: Python-转换元组列表(除非可以修改答案以创建JSON字符串作为输出).
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?
推荐答案
There is a much better way to generate JSON strings: the json
module.
import json
rs = json.dumps(dict(lst))
这利用了以下事实:dict()
可以采用一系列键-值对(二值元组)并将其转换为映射,json
模块直接将其转换为JSON对象结构.
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.
演示:
>>> import json
>>> lst = [("name", "value"), ("name2", "value2")]
>>> rs = json.dumps(dict(lst))
>>> print rs
{"name2": "value2", "name": "value"}
这篇关于从元组列表格式化JSON字符串的更多pythonic方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!