【问题标题】:python search for a string in jsonpython在json中搜索字符串
【发布时间】:2020-04-12 10:32:59
【问题描述】:

Json table_data

[
  {
    "country": "country one",
    "city": "city one",
    "Start Time": "21th December 2019 09:00 AM",
    "End time": "22th December 2019 03:00 PM"
  },
  {
   "country": "country two",
    "city": "city two",
    "Start Time": "23th December 2019 09:00 AM",
    "End time": "23th December 2019 03:00 PM"
  },
  {
 "country": "country three",
    "city": "city three",
    "Start Time": "24th December 2019 09:00 AM",
    "End time": "24th December 2019 03:00 PM"
  } 
]

所以我想要做的是寻找一个国家,一旦我找到了你想打印相关数据的国家 到目前为止我已经这样做了

for dt in table_data:# this is not correct i think
    if("country one" == dt):
        print()

我不知道如何在 python 中解决这个问题 任何帮助将不胜感激

【问题讨论】:

  • 我建议您阅读有关 Python 的教程。具体来说,您需要了解字典以及如何使用它们。
  • if dt['country'] == "country one":
  • @Code-Apprentice 这是 Python,不是 JS。
  • @Barmar 哎呀。谢谢你的收获。我想我看到了 JSON 标记并跳转到 JavaScript。

标签: python json string


【解决方案1】:

我建议你从更简单的开始。假设您有一个country 对象:

country = {
    "country": "country one",
    "city": "city one",
    "Start Time": "21th December 2019 09:00 AM",
    "End time": "22th December 2019 03:00 PM"
  }

现在我们需要一个函数来打印这个对象:

def print_country(c):
    pass

第一步是弄清楚如何填写这个函数的细节。

【讨论】:

    【解决方案2】:

    试试:

    import json
    
    data = json.loads("""
    [
      {
        "country": "country one",
        "city": "city one",
        "Start Time": "21th December 2019 09:00 AM",
        "End time": "22th December 2019 03:00 PM"
      },
      {
       "country": "country two",
        "city": "city two",
        "Start Time": "23th December 2019 09:00 AM",
        "End time": "23th December 2019 03:00 PM"
      },
      {
     "country": "country three",
        "city": "city three",
        "Start Time": "24th December 2019 09:00 AM",
        "End time": "24th December 2019 03:00 PM"
      } 
    ]
    """)
    
    for this_country in data:
        if this_country['country'] == 'country two':
            print("\n".join([": ".join(k) for k in this_country.items()]))
    

    输出:

    country: country two
    city: city two
    Start Time: 23th December 2019 09:00 AM
    End time: 23th December 2019 03:00 PM
    

    【讨论】:

      【解决方案3】:

      类似的东西。

      for data in table_data:
          if data['country'] == 'country one':
              print(data)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-07-04
        • 1970-01-01
        • 1970-01-01
        • 2015-05-28
        • 2015-12-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多