- Java Script Object Notation (JSON) is an easy to read and write data-interchange format
- JSON is a lightweight format for storing and transporting data
- JSON is often used for transfer of data in Client Server applications
- JSON format is used for serializing and transmitting data over a network connection, for example, transmitting data between a server and web application
- It's used by lots of APIs and Databases, and it's easy for both humans and machines to read
- JSON represents objects as name/value pairs
- JSON is used as an alternative to XML and it is easy for machines to parse and generate
- Exchange of information encoded as JSON involves encoding and decoding steps
Syntax to be followed in JSON
- Data is in name/value pairs
- Data is separated by commas
- Curly braces hold objects
- Square brackets hold arrays
Example:
person={"name":"Dr VP","langauges":["English","Kokani","Hindi","Kannada"]}
JSON libraries are available for many programming languages and systems like the following:
- ActionScript
- C
- C++
- C#
- Cold Fusion
- Java
- Lisp
- Perl
- Objective-C
- PHP
- Python
- Ruby etc.
JSON and Python
- Since exchange of information encoded as JSON involves encoding and decoding steps
- The python package for JSON provides function for encoding and decoding JSON
- Python has a built-in package called JSON, which is used to work with JSON data. So you need to import json
- If you have a Python object, you can convert it into a JSON object i.e. string by using the json.dumps() method
- Similarly you can use json.loads() method to parse JSON object i.e. string which results in a dictionary
Program:
Output
One more program: In the following program json.dumps() is used directly in the print function and a string i.e. json object is passed as an argument to json.load() function which returns a dictionary and the values of the keys are displayed.
Program:
Output
Writing JSON to a file in Python
- You can use “write” function to store the JSON object in a file
- As we know json.dump() is used to convert Python dictionary to JSON object
Reading JSON from a file using Python
- The json.load() method is used for reading the JSON object
- It loads the JSON content from a JSON file into a dictionary. It takes one parameter
Program:
Output:
Our aim is to provide information to the knowledge
seekers.