Home » Python22 February 2016

Python: Read Write JSON

In this article, I will be showing how to read data from a JSON file and write data to a new JSON file using Python programming language.

Suppose, I have the following JSON data which is saved in a file named sample-1.json.

Download: sample-1.json

As you can see from the above JSON data that each JSON entry has a key ‘type‘ having value user, review, or business. The type key distinguishes whether the entry is about user, business, or review.

From this JSON file, we will be selecting entries based on “type”, i.e. we will be selecting entries for user, entries for business, and entries for review. And then, we will be saving each of them in a separate JSON files.

We will be creating a new JSON file (sample-user.json) for users and saving all user data in it. Similarly, we will be creating a new JSON file (sample-business.json) for businesses and saving all business data in it.

However, there is a slight difference logic for reviews. We will filter the reviews by category. We will only select those reviews which falls under Food or Beauty and Spas category and save them to a new JSON file (sample-review.json).

Here’s the full source code:

Here are the user, business and review JSON files created from above code:

sample-user.json | sample-business.json | sample-review.json

Hope this helps.


Get New Post by Email

Find me on

FacebookTwitterGoogle+LinkedInRSS Feed

Comments are closed.