Umer
Umer

Reputation: 97

Unable to format the output of a link in python

I am trying to access weather api data. It returns a long a less human readable single line. I am trying to replace every bracket({) with '{/n' so that bracket remains but as well a new line character just for better readable json. But it returns every character on a new line in the shell.

import urllib2

url2 = 'http://api.openweathermap.org/data/2.5/find?q=london,PK&units=metric'
data = urllib2.urlopen(url2)
s = data.read()
count = 0
s = s.replace('{',"{\n")
#s = ''.join(s)
for line in s:
    print line
    count = count + 1
print count

after join() the problem still persists. The problematic output after this code is like thisenter image description here

Upvotes: 0

Views: 59

Answers (3)

Tim
Tim

Reputation: 2592

The issue is here:

for line in s:
    print line

At this point, it will print every character on a separate line - that's what print does (it adds a trailing newline to each print command), as shown by this code:

print 1
print
print 2

which outputs this:

1

2

You may be confused with the name line, but it's not a special variable name. You can change the word line to any valid variable name and it will work the same way.

A for loop will iterate over an iterable. If it's a file, it will do each line. A list will be each element, and a string goes over every character. Because you say to print it, it then prints them individually.

Are you expecting a non-string response from the API? If it gives a list like this:

["calls=10","message=hello"]

then your for loop will print each in turn. But if it's just a string, like "message=hello" it will print each character.


And the reason there is a blank newline after the {? Because the replace command is working fine.

Upvotes: 3

bgporter
bgporter

Reputation: 36464

Why don't you use the built-in capabilities of the json library that's standard in Python?

import urllib2
import json

url2 = 'http://api.openweathermap.org/data/2.5/find?q=london,PK&units=metric'
data = urllib2.urlopen(url2)

# read the contents in and parse the JSON.
jsonData = json.loads(data.read())

# print it out nicely formatted:
print json.dumps(jsonData, sort_keys=True, indent=4, separators=(',', ': '))

output:

{
    "cod": "200",
    "count": 1,
    "list": [
        {
            "clouds": {
                "all": 20
            },
            "coord": {
                "lat": 38.7994,
                "lon": -89.9603
            },
            "dt": 1442072098,
            "id": 4237717,
            "main": {
                "humidity": 67,
                "pressure": 1020,
                "temp": 16.82,
                "temp_max": 18.89,
                "temp_min": 15
            },
            "name": "Edwardsville",
            "sys": {
                "country": "United States of America"
            },
            "weather": [
                {
                    "description": "few clouds",
                    "icon": "02d",
                    "id": 801,
                    "main": "Clouds"
                }
            ],
            "wind": {
                "deg": 350,
                "speed": 4.6
            }
        }
    ],
    "message": "accurate"
}

Upvotes: 3

smheidrich
smheidrich

Reputation: 4519

s is just a string, so doing for x in s actually iterates over individual characters of s, not over its lines. I think you're confusing it with for line in f when f is a file object!

Upvotes: 1

Related Questions