如何在写入文件时格式化JSON数据

时间:2016-07-09 15:52:02

标签: python json api formatting request

我试图获取此api请求,并在将其转储到JSON文件时对其进行格式化。每当我这样做,它的所有字符串都非常难以阅读。我尝试添加缩进但它没有做任何事情。如果需要,我可以提供API密钥。

import json, requests

url = "http://api.openweathermap.org/data/2.5/forecast/city?id=524901&APPID={APIKEY}"
response = requests.get(url)
response.raise_for_status()

with open('weather.json', 'w') as outfile:
     json.dump(response.text, outfile, indent=4)

2 个答案:

答案 0 :(得分:5)

我认为您的代码存在一些问题。

首先,在不同的行上编写不相关的导入而不是用逗号分隔,这被认为是更好的形式。我们通常只在使用from module import thing1, thing2时才使用逗号。

我假设您将{APIKEY}作为占位符留在了网址中,但为了以下情况:您需要在那里插入您的 API密钥。您可以按原样.format来完成此操作。

您致电response.raise_for_status()。这应该包含在try / except块中,因为如果请求失败,则引发异常。你的代码只是barf,那时你就是SOL。

但这是最重要的事情:response.text 是一个字符串json.dump仅适用于词典。你需要一本字典,所以用response.json()来获取它。 (或者,如果您想先操作JSON,可以通过执行json_string = json.loads(response.text)从字符串中获取它。)

以下是它应该出现的内容:

import json
import requests

# Replace this with your API key.
api_key = '0123456789abcdef0123456789abcdef'

url = ("http://api.openweathermap.org/data/2.5/forecast/city?"
       "id=524901&APPID={APIKEY}".format(APIKEY=apiKey))
response = requests.get(url)

try:
    response.raise_for_status()
except requests.exceptions.HTTPError:
    pass
    # Handle bad request, e.g. a 401 if you have a bad API key.

with open('weather.json', 'w') as outfile:
     json.dump(response.json(), outfile, indent=4)

答案 1 :(得分:0)

with open('weather.json', 'w') as outfile: json.dump(response.json(), outfile, indent=4) # response.json() is here now :) 是你的朋友。我已经测试了下面的代码(当然使用不同的API端点返回json数据),它对我来说很好,如果这对你有用,请告诉我。

package com.androidnik.tourguide;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

import com.androidnik.tourguide.AmusmentsFragment;
import com.androidnik.tourguide.HotelRestaurantsFragment;
import com.androidnik.tourguide.MustVisitFragment;
import com.androidnik.tourguide.ToDoList;
import com.androidnik.tourguide.ToDoListFragment;

private String tabTitles[] = new String[] { "Numbers", "Family", "Color", "Phrases" };

public MyFragmentAdapter(FragmentManager fm) {
    super(fm);
}

@Override
public Fragment getItem(int position) {
    if (position == 0) {
        return new MustVisitFragment();
    } else if (position == 1){
        return new ToDoListFragment();
    } else if(position == 2){
        return new HotelRestaurantsFragment();
    }
    else
        return new AmusmentsFragment();
}

@Override
public int getCount() {
    return 4;
}

@Override
public CharSequence getPageTitle(int position) {
    return tabTitles[position];
}
}
相关问题