cari

Rumah  >  Soal Jawab  >  teks badan

python - 假定有json数据多条记录,如何根据KEY的值返回一条记录?

比如说给一个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中文网2786 hari yang lalu977

membalas semua(1)saya akan balas

  • 天蓬老师

    天蓬老师2017-04-18 10:29:59

    Andaikan terdapat rentetan json seperti berikut:

    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"
      }
    ]
    """

    Kod:

    # 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)

    Keputusan:

    [{'Name': 'C4', 'No': '0542', 'createDate': '9999/12/31 00:00:00', 'lastUpdDate': '9999/12/31 00:00:00'}]

    Soalan yang saya jawab: Python-QA

    balas
    0
  • Batalbalas