Python flask处理多栏json数据


如果我有一个元组:
((1,'a','blahblah'),(2,'b','blahblah'),(3,'c','blahblah'),...)

想要返回的json格式大概是:


 items: Array[100]
0:Object
    {
        'pmid': 1,
        'title': 'a',
        'abstract': 'blahblah'
    }
1:Object
    {
        'pmid': 2,
        'title': 'b',
        'abstract': 'blahblah'
    }
2:Object
    {
        'pmid': '3',
        'title': 'b',
        'abstract': 'blahblah'
    }

...

python代码该如何写?

flask json python2.7

三千东流水 10 years ago

 source = ((1,'a','blahblah'),(2,'b','blahblah'),(3,'c','blahblah'),...)
result = map(lambda x: dict(zip(('pmid', 'title', 'abstract'), x)), source)

薙切·绘里奈 answered 10 years ago

如下代码:


 import json
result = json.dumps(map(lambda a: dict(zip(('pmid', 'title', 'abstract'), a)), ((1,'a','blahblah'),(2,'b','blahblah'),(3,'c','blahblah'))))

结果:
'[{"pmid": 1, "abstract": "blahblah", "title": "a"}, {"pmid": 2, "abstract": "blahblah", "title": "b"}, {"pmid": 3, "abstract": "blahblah", "title": "c"}]'


 请输入代码

Sevion answered 10 years ago

json python 里对应的数据结构大致为 字典 ,也就是你需要先把 tuple 转换成 dictionary ,然后再用标准库 json 进行 dumps 一下


 import json

t = ((1,'a','blahblah'),(2,'b','blahblah'),(3,'c','blahblah'),...)
key = ('pmid', 'title', 'abstract')

d = [dict(zip(key, value)) for value in t]

res_json = json.dumps(d)

字典的key是没有顺序的,如果要保证顺序,可以使用 collections 下的 OrderedDict 结构拼装

奈須ゆきこ answered 10 years ago

Your Answer