How to Print Particular JSON Value in Python?

JSON is an abbreviation for JavaScript Object Notation. It means that data is stored and transferred using a script (executable) file comprised of text in a computer language. Python has a built-in library named json that handles JSON. In order to use this feature, we must first load the json package into our Python script. The text in JSON is represented by a quoted-string, which contains the value in the key-value mapping within flower braces { }.

How to Read from JSON?

In Python, loading a JSON object is simple. Python includes a library named json that may be used to work with JSON data. It is accomplished by utilizing the JSON module, which gives us a plethora of methods, among which the loads() and load() methods will assist us in reading the JSON file.

Here we take demo.json as an Example

{
"id": 1,
 "name": "virat",
 "Address": [{
   "city" : "hyderabad",
   "state": "telangana",
   "geo": {
        "lat": 90,
        "long": 100
          }
        }]
 }

Printing Particular JSON Value in Python

Approach:

  • Import json module using the import keyword
  • Open some random json file using the open() function by passing the filename/path as an argument to it and store it in a variable
  • Load/get the content of the given json file using the load() function of the json module and store it in another variable
  • Print the data of the given JSON file
  • Get a specific value from the json file using slicing
  • Printing Address details from a given JSON file.
  • Printing ‘geo’ details in Address.
  • Printing ‘lat’ details in Address/geo.
  • The Exit of the Program.

Below is the implementation:

# Import json module using the import keyword
import json
# Open some random json file using the open() function by passing the
# filename/path as an argument to it and store it in a variable
gvn_jsonfile = open("demo.json")
# Load/get the content of the given json file using the load() function of the
# json module and store it in another variable
json_data = json.load(gvn_jsonfile)
# Print the data of the given JSON file
print("The data of the given JSON file:\n", json_data)
print()
# Get a specific value from the json file using slicing
# Printing Address details from a given JSON file
print("Printing Address details:")
print(json_data["Address"])
print()
# Printing 'geo' details in Address
print("Printing 'geo' details in Address:")
print(json_data["Address"][0]["geo"])
print()
# Printing 'lat' details in Address/geo
print("Printing 'lat' details in Address/geo:")
print(json_data["Address"][0]["geo"]["lat"])

Output:

The data of the given JSON file:
{'id': 1, 'name': 'virat', 'Address': [{'city': 'hyderabad', 'state': 'telangana', 'geo': {'lat': 90, 'long': 100}}]}

Printing Address details:
[{'city': 'hyderabad', 'state': 'telangana', 'geo': {'lat': 90, 'long': 100}}]

Printing 'geo' details in Address:
{'lat': 90, 'long': 100}

Printing 'lat' details in Address/geo:
90