JSON
JSON (JavaScript Object Notation)
JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write, and easy for machines to parse and generate. It is a text format that is completely language-independent but uses conventions that are familiar to programmers of the C family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others.
JSON Syntax:
JSON data is represented as key-value pairs and uses curly braces {}
to define objects and square brackets []
to define arrays. Here is a basic overview of JSON syntax:
- Objects: Represented by curly braces
{}
and consist of key-value pairs separated by commas. Keys and values are strings, and the key is followed by a colon.
{
"name": "John",
"age": 30,
"city": "New York"
}
[]
and contain ordered lists of values. Values can be strings, numbers, objects, arrays, true
, false
, or null
.
["apple", "banana", "cherry"]
true
or false
), or null
.
"Hello, World!"
Example JSON Data:
{
"name": "Alice",
"age": 25,
"isStudent": true,
"grades": [90, 85, 92],
"address": {
"city": "Wonderland",
"country": "Fictional Land"
},
"languages": ["English", "French"]
}
JSON in Python:
Python provides a built-in module called json
for encoding and decoding JSON data.
Encoding (Python to JSON):
import json
data = {
"name": "Alice",
"age": 25,
"isStudent": True,
"grades": [90, 85, 92],
"address": {
"city": "Wonderland",
"country": "Fictional Land"
},
"languages": ["English", "French"]
}
json_data = json.dumps(data, indent=2) # Converts Python data to JSON string
print(json_data)
Decoding (JSON to Python):
import json
json_data = '''
{
"name": "Alice",
"age": 25,
"isStudent": true,
"grades": [90, 85, 92],
"address": {
"city": "Wonderland",
"country": "Fictional Land"
},
"languages": ["English", "French"]
}
'''
python_data = json.loads(json_data) # Converts JSON string to Python data
print(python_data)
The json.dumps()
function is used for encoding Python data to a JSON-formatted string, and json.loads()
is used for decoding a JSON string to Python data.
JSON is commonly used for data exchange between a server and a web application, configuration files, and various other scenarios where a simple and human-readable data format is required.