Heim > Fragen und Antworten > Hauptteil
比如说给一个json数据:
[
{
"Name": "A1",
"No": "3111",
"createDate": "9999/12/31 00:00:00",
"lastUpdDate": "9999/12/31 00:00:00"
},
{
"Name": "B2",
"No": "2222",
"createDate": "9999/12/31 00:00:00",
"lastUpdDate": "9999/12/31 00:00:00"
},
{
"Name": "C3",
"No": "1444",
"createDate": "9999/12/31 00:00:00",
"lastUpdDate": "9999/12/31 00:00:00"
},
{
"Name": "C4",
"No": "0542",
"createDate": "9999/12/31 00:00:00",
"lastUpdDate": "9999/12/31 00:00:00"
}
]
我想要No为"0542"的一条记录:
{
"Name": "C4",
"No": "0542",
"createDate": "9999/12/31 00:00:00",
"lastUpdDate": "9999/12/31 00:00:00"
}
如果用python3应该怎么实现?
我网上搜索了类似代码
比如 data = list(filter(lambda d: d['No'] == "0542", jsondata))
改来改去,总是报各种类型错误,抓狂了……所以请教下大家,应该怎么写,谢谢!
天蓬老师2017-04-18 10:29:59
假設有 json string 如下:
s = """
[
{
"Name": "A1",
"No": "3111",
"createDate": "9999/12/31 00:00:00",
"lastUpdDate": "9999/12/31 00:00:00"
},
{
"Name": "B2",
"No": "2222",
"createDate": "9999/12/31 00:00:00",
"lastUpdDate": "9999/12/31 00:00:00"
},
{
"Name": "C3",
"No": "1444",
"createDate": "9999/12/31 00:00:00",
"lastUpdDate": "9999/12/31 00:00:00"
},
{
"Name": "C4",
"No": "0542",
"createDate": "9999/12/31 00:00:00",
"lastUpdDate": "9999/12/31 00:00:00"
}
]
"""
代碼:
# code for python3
import json
def search(json_str, no):
return [datum for datum in json.loads(s) if datum['No']==no]
datum = search(s, '0542')
print(datum)
結果:
[{'Name': 'C4', 'No': '0542', 'createDate': '9999/12/31 00:00:00', 'lastUpdDate': '9999/12/31 00:00:00'}]
我回答過的問題: Python-QA