【python】yield方式读取json信息

yield方式读取json信息

# -- coding:utf-8 --
import json


def get_info_url_generate():
    with open('test.json', 'r', encoding='utf-8') as f:
        setting = json.load(f)
        msgs = setting["msgs"]
        for info in msgs:
            infos = []
            info_id = info['id']
            info_name = info['name']
            info_city = info['city']
            infos.append(info_id)
            infos.append(info_name)
            infos.append(info_city)
            try:
                if info_name:
                    yield infos
            except:
                break


if __name__ == '__main__':
    infos = get_info_url_generate()
    for i in range(4):
        info_url, info_id, info_class = next(infos)
        print(info_url, info_id, info_class)

test.json:

{
  "title": "熊猫",
  "msgs": [
    {"id": 1,"name": "vency","city": "上海"},
    {"id": 2,"name": "wusuowei","city": "北京"},
    {"id": 3,"name": "lily","city": "北京"},
    {"id": 4,"name": "bill","city": "上海"}
  ]
}

结果:

1 vency 上海
2 wusuowei 北京
3 lily 北京
4 bill 上海

你可能感兴趣的:(Python,实用工具,json)