在JSON fi中对组排序

2024-06-11 22:01:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从这个JSON页面('https://oa.ceair.com/common_source/airport/en_AU.json?v=1561031507803&_=1561031507712')收集一些信息,并将其转换为本地硬盘上的文本文件。 更具体地说,我只需要“match”、“label”和“value”上的字符串

import os, re, requests
def getCity():

  url='https://oa.ceair.com/common_source/airport/en_AU.json? 
       v=1561031507803&_=1561031507712'
  response=requests.get(url,verify=True)
  city=re.findall('([A-Z]+)',response.text)
  city=str(city)
  write(city)

使用上面的代码,信息已经成功地输入到另一个文本文件中,但是,它包含了所有的原始数据


Tags: httpsrecom信息jsoncitysourcecommon
1条回答
网友
1楼 · 发布于 2024-06-11 22:01:11

因为它是json,所以很容易使用。请求具有对它的内置支持。Response的json方法返回一个dict,我们可以很容易地使用它:

import requests

response = requests.get(r"https://oa.ceair.com/common_source/airport/en_AU.json?v=1561031507803&_=1561031507712", verify=True)
airports = response.json()

with open(r"airport_info.txt", "wt") as f:
    for airport in airports:
        f.write(f"match: {airport['match']}\n") # Literal string interpolation
        f.write(f"label: {airport['label']}\n") # See https://realpython.com/python-f-strings/
        f.write(f"value: {airport['value']}\n")

airport_info.txt如下所示,适用于1258行:

match: SYD,SYDNEY KINGSFORD SMITH APT,XiNiJinSiFuTe·ShiMiSiJiChang,XNJSFT·SMSJC
label: SYDNEY KINGSFORD SMITH APT, SYD
value: SYD
match: MEL,MELBOURNE,MoErBen,MEB
label: MELBOURNE, MEL
value: MEL

等等

相关问题 更多 >