首页 > 解决方案 > 用 requests.get 编写一个 get json 函数,而 json 文件是单引号的

问题描述

我正在编写一个使用 requests.get 获取 json 原始文件的函数,将其写入文件,将所有单引号转换为双引号(api 输出带有单引号的 json 文件),将其写入文件,然后返回数据。我写的那个根本行不通,如果行了,两次写入和读取物理文件仍然很草率。有没有可能提高效率的方法?

def getInfo(type):
    PARAMS = {
        'token': '',
        'type': type, }
    URL = urljoin(host, '/data')
    response = requests.get(url=URL, params=PARAMS).json()

    try:
        os.mkdir('json')
    except:
        pass

    jsonFile = open(os.path.join('json', type + ".json"),
                    "w").write(str(response))

    filer = open(os.path.join('json', type + '.json'), 'r')
    file = open(os.path.join('json', type + '.json'), 'w')
    for line in filer:
        # read replace the string and write to output file
        file.write(line.replace("'", '"'))
    file.close()
    jsonFile = open(os.path.join('json', type + ".json"),
                    "w").write(str(file))
    with open(os.path.join('json', type + ".json")) as f:
        data = json.loads(f.read())

    return data

例子.json

[{'api_member_id': 14171432, 'api_id': 1, 'api_name': 'No.1', 'api_name_id': '', 'api_mission': [0, 0, 0, 0], 'api_flagship': '0', 'api_ship': [341, 38, 317, 345, 145, 50]}, {'api_member_id': 14171432, 'api_id': 2, 'api_name': 'No.2', 'api_name_id': '', 'api_mission': [0, 0, 0, 0], 'api_flagship': '0', 'api_ship': [13, 19, 118, 36, -1, -1]}, {'api_member_id': 14171432, 'api_id': 3, 'api_name': 'No.3', 'api_name_id': '', 'api_mission': [0, 0, 0, 0], 'api_flagship': '0', 'api_ship': [58, 167, 14, 146, -1, -1]}, {'api_member_id': 14171432, 'api_id': 4, 'api_name': 'No.4', 'api_name_id': '', 'api_mission': [0, 0, 0, 0], 'api_flagship': '0', 'api_ship': [-1, -1, -1, -1, -1, -1]}]

标签: pythonjsonpython-requests

解决方案


谢谢@Epsi95

def getInfo(type, debug=False):
    PARAMS = {
        'token': '',
        'type': type}
    URL = urljoin(host, '/data')
    response = requests.get(url=URL, params=PARAMS).text.replace("'", '"')
    
    if debug is True:
        mkdir('json')
        jsonFile = open(os.path.join('json', type + ".json"),
                        "w", encoding='utf-8').write(str(response))
    return json.loads(response)```

推荐阅读