Posted inPython

How to Extract data from JSON file in Python?

Today, We want to share with you python extract data from json file.In this post we will show you parse, read and write JSON in Python, hear for convert JSON to dict and pretty print it we will give you demo and example for implement.In this post, we will learn about Convert CSV Data To JSON Using JavaScript with an example.

Extract part of data from JSON file with python

Sometimes i need to extract text data from JSON file for our all the products analysis.

here simple creates new products object for each object with:

my_product={}

Moreover, it overwrites the previous contents of the variable. Old products in m_product is deleted from memory.

Try to create a list before your for loop and store the result there.
Example 1:

result = []
for item in json_decode:
    my_product={}
    my_product['title']=item.get('labels').get('en').get('value')
    my_product['description']=item.get('descriptions').get('en').get('value')
    my_product['id']=item.get('id')
    print(my_product)
    result.append(my_product)

Finally, write the result to the output:

back_json=json.dumps(result)

How to read data from JSON file?

Example 2: Read JSON Data for Analysis

import requests
import json
 
response = requests.get("https://api.yourdomainname.com/hc/en-us/uploads/22504785/products.json")
output = response.json()
 
# Extract specific node content.
print(output['pname']['price'])
 
# Dump data as string
data = json.dumps(output)
print(data)

Import json Module

import json

Parse JSON in Python
The using json module creates it simple to parse JSON strings as well as all files containing JSON object.

Example : Python JSON to dict

import json

member = '{"name": "jkpaysys", "moviestype": ["Tamil", "Hindi"]}'
member_dict = json.loads(member)

# Output: {'name': 'jkpaysys', 'moviestype': ['Tamil', 'Hindi']}
print( member_dict)

# Output: ['Tamil', 'Hindi']
print(member_dict['moviestype'])

Example : Python read JSON file
You can use json.load() method to read a file containing JSON object.

For Example, you have a file named member.json which all the data contains a JSON object.


{"name": "jkpaysys", 
"moviestype": ["Tamil", "Hindi"]
}

parse this json file:


import json

with open('path_to_file/member.json') as f:
  data = json.load(f)

# Output: {'name': 'jkpaysys', 'moviestype': ['Tamil', 'Hindi']}
print(data)

Python Convert to JSON string

You can convert a dictionary to JSON string using json.dumps() method.

Convert dict to JSON

import json

member_dict = {'name': 'jkpaysys',
'age': 12,
'children': None
}
member_json = json.dumps(member_dict)

# Output: {"name": "jkpaysys", "age": 12, "children": null}
print(member_json)

Here’s a table showing Python objects and their equivalent conversion to JSON.

Python JSON Equivalent
dict object
list, tuple array
str string
int, float, int number
True true
False false
None null

Python pretty print JSON

Example


import json

member_string = '{"name": "jkpaysys", "moviestype": "Tamil", "numbers": [2, 1.6, null]}'

# Getting dictionary
member_dict = json.loads(member_string)

# Pretty Printing JSON string back
print(json.dumps(member_dict, indent = 4, sort_keys=True))

output


{
    "moviestype": "Tamil",
    "name": "jkpaysys",
    "numbers": [
        2,
        1.6,
        null
    ]
}

Writing JSON to a file


import json

member_dict = {"name": "jkpaysys",
"moviestype": ["Tamil", "Hindi"],
"married": True,
"age": 32
}

with open('member.txt', 'w') as json_file:
  json.dump(member_dict, json_file)

When you run the program, the member.txt file will be created. The file has following text inside it.


{"name": "jkpaysys", "moviestype": ["Tamil", "Hindi"], "married": true, "age": 32}

I hope you get an idea about extracting data from json python assignment.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

I am Jaydeep Gondaliya , a software engineer, the founder and the person running Pakainfo. I'm a full-stack developer, entrepreneur and owner of Pakainfo.com. I live in India and I love to write tutorials and tips that can help to other artisan, a Passionate Blogger, who love to share the informative content on PHP, JavaScript, jQuery, Laravel, CodeIgniter, VueJS, AngularJS and Bootstrap from the early stage.

Leave a Reply

Your email address will not be published. Required fields are marked *

We accept paid guest Posting on our Site : Guest Post Chat with Us On Skype