【问题标题】:Not getting the correct JSON format from pulled API data [closed]未从提取的 API 数据中获取正确的 JSON 格式 [关闭]
【发布时间】:2021-12-07 15:59:45
【问题描述】:

我正在尝试将此输出转换为正确的 JSON 格式。不幸的是,这并没有真正奏效。来自 API 拉取的所有数据都存储在一个列表中,然后我读取该列表以对其进行优化并仅获取我需要的数据。

def refine_data():
    with open("api-pull.json", encoding='utf-8') as json_file:
        json_data = json.load(json_file)
        print('JSON loaded correctly')
        
        
        with open('REFINEDapi-pull.json', 'w', encoding='utf-8') as REFINED:
            for s in range(len(json_data)):
                
                if 'lat' in json_data[s] and 'lng' in json_data[s]: #if coordinates exist
                    
                    json.dump({
                        'name' : json_data[s]["name"],
                        'latitude' : json_data[s]["lat"],
                        'longitude' : json_data[s]["lng"],
                        'status' : json_data[s]["status"]["online"],
                        'address' : json_data[s]["address"],
                        'reward_scale' : json_data[s]["reward_scale"]
                        }, REFINED, ensure_ascii=False, indent=4)

我当前输出的小样本:

我想要完成的示例:

【问题讨论】:

  • 从您的问题中不清楚您想要获得什么或什么不适合您。
  • @coppereyecat 对不起。 StackOverflow 的新手。我添加了一个指向屏幕截图的链接,显示我得到的 JSON 格式不正确。
  • 你想得到什么格式?你的输出有什么问题?
  • 虽然我怀疑问题是你一次转储一个对象,而不是整个数组。
  • 我添加了一张我想要得到的结果的图片。

标签: python json api append json-deserialization


【解决方案1】:

您应该做的是将您创建的dicts 附加到一个列表中,然后将json.dump() 单个列表附加到文件中:

def refine_data():
    with open("api-pull.json", encoding='utf-8') as json_file:
        json_data = json.load(json_file)
        print('JSON loaded correctly')        
        
        with open('REFINEDapi-pull.json', 'w', encoding='utf-8') as REFINED:
            result = []   # start a list here
            for s in range(len(json_data)):
                if 'lat' in json_data[s] and 'lng' in json_data[s]: #if coordinates exist
                    result.append({
                        'name' : json_data[s]["name"],
                        'latitude' : json_data[s]["lat"],
                        'longitude' : json_data[s]["lng"],
                        'status' : json_data[s]["status"]["online"],
                        'address' : json_data[s]["address"],
                        'reward_scale' : json_data[s]["reward_scale"]
                        })

            json.dump(result, REFINED, ensure_ascii=False, indent=4)

【讨论】:

  • 这正是我想要的。非常感谢!这更有意义。
猜你喜欢
  • 2020-09-23
  • 1970-01-01
  • 1970-01-01
  • 2020-07-14
  • 2019-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多