0

I need to make an API that gets text from a website and a country's name. Then it tells me if the country's population is going up or down or not changing. But not i'm stuck at figuring out how to get the population number from such a long string.

the string is this:

{"googleMaps":"https://goo.gl/maps/6UY1AH8XeafVwdC97","openStreetMaps":"https://www.openstreetmap.org/relation/1473946"},"population":9216900,"gini":{"2016":39.0},"fifa":"ISR","car":{"signs":["IL"],"side":"right"}

And I want to get just the number "9216900" out of there and save it as an int.

I've tried to user json.loads but I get this error:

Traceback (most recent call last): File "G:/HackerU/Python/Challenges/Population/main.py", line 12, in loaded_json = json.loads(json_data)[:-1][2:] File "C:\Users\netanell\AppData\Local\Programs\Python\Python38-32\lib\json_init_.py", line 357, in loads return _default_decoder.decode(s) File "C:\Users\netanell\AppData\Local\Programs\Python\Python38-32\lib\json\decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\Users\netanell\AppData\Local\Programs\Python\Python38-32\lib\json\decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

this is the current code:

import bs4
import urllib.request
import json

country = input("Country: ")
# Getting updated list and saving it as "json_data"
link = 'https://restcountries.com/v3.1/name/' + country
webpage = str(urllib.request.urlopen(link).read())
soup = bs4.BeautifulSoup(webpage, "html.parser")
json_data = soup.get_text()
loaded_json = json.loads(json_data)[:-1][2:]
population_number = loaded_json['population']
print(population_number)
  • Is that saved as a string or `dict`? – Scrapper142 Nov 30 '21 at 00:11
  • Your data is in the extremely common JSON format, which you **must** understand in order to do web programming. Once you have parsed the data using a library (Python includes support in the standard library), you deal with the resulting data *the exact same way that you would deal with any other nested lists and/or dictionaries*. (If you don't know how to work with a `dict` in Python, then you need to follow a tutorial and learn the fundamentals; walk before you can run.) – Karl Knechtel Nov 30 '21 at 00:14

1 Answers1

1

This string is stored as JSON (Javascript Object Notation), so you can parse that into python very simply. See below

import json

string = "..." # Your string

loaded_json = json.loads(string)

population_number = loaded_json['population']
print(population_number)

This converts that text to a python Dictionary, allowing you access it as such.

HPringles
  • 1,042
  • 6
  • 15