Q:

How to read JSON from URL requests in python?

0

How to read JSON from URL requests in python

In this exercise, you will learn how to read JSON from URL requests using Python.

JSON (JavaScript Object Notation) is a lightweight, open standard, data-interchange format. It is easy to read and write for humans. It is used primarily to transmit data between a web application and a server. Today, it is more popular than XML.

In this exercise, we have imported two modules - JSON and urllib.request. The JSON module is an in-built package of Python and is used to work with JSON data. It offers a function json.loads to parse the JSON string.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

import urllib.request
import json

def getData(url):
    response = urllib.request.urlopen(url)
    if(response.getcode()==200):
        data = response.read()
        jsonData = json.loads(data)
    else:
        print("Error occured", response.getcode())
    return jsonData

def main():
    url = "https://www.etutorialspoint.com/countries.json"
    data = getData(url)
    # print the country name and capital
    for i in data["countries"]:
         print(f'Name: {i["country"]["country_name"]}, Capital: {i["country"]["capital"]}')

if __name__ == '__main__':
    main()

When we run the above code, the output will look like this -

Python read JSON from URL

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Exercises, Practice Questions and Solutions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Write a node.js program for making external http c... >>
<< How do you count consonants in a string in python?...