python - 假定有json数据多条记录,如何根据KEY的值返回一条记录?
PHP中文网
PHP中文网 2017-04-18 10:27:59
0
1
970

比如说给一个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))
改来改去,总是报各种类型错误,抓狂了……所以请教下大家,应该怎么写,谢谢!

PHP中文网
PHP中文网

认证高级PHP讲师

全部回覆(1)
Peter_Zhu

假設有 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

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板