JSON is an important data exchange format used in modern software development. Here are some reasons why JSON is important:
Lightweight: JSON is a lightweight data interchange format that can be easily transferred over the network. Its syntax is simpler than other formats like XML, which makes it faster to parse and process.
Human-readable: JSON is human-readable, which means it is easy for developers to read and understand the data contained within. This makes it easier to debug and troubleshoot issues that may arise.
Cross-platform: JSON is supported by a wide range of programming languages and platforms, making it easy to exchange data between different systems.
Widely used: JSON is widely used in modern software development for data exchange between web services, client-server communication, and data storage.
Easy to use: JSON is easy to use in Python and other programming languages, with built-in libraries and functions for converting data to and from JSON.
So we will study some uses of JSON with Pythons as the following :
To format the JSON result, you can use the json.dumps() function’s optional arguments.
Here are some common arguments that can be used to format the JSON output:
indent:
specifies the number of spaces to use for indentation.
For example, json.dumps(data, indent=4) will format the JSON with an indentation of 4 spaces per level.
sort_keys:
sorts the keys of the JSON object alphabetically.
For example, json.dumps(data, sort_keys=True) will sort the keys in the JSON object alphabetically.
separators:
allows you to specify custom separators for the JSON object.
For example, json.dumps(data, separators=(“,”, ” = “)) will use a comma as the key-value separator and an equals sign as the value separator.
ensure_ascii:
specifies whether to escape non-ASCII characters in the output. The default value is True, which means non-ASCII characters will be escaped. If you want to include non-ASCII characters in the output, you can set ensure_ascii to False.
Here’s an example that demonstrates how to use some of these optional arguments:
import json
data = {
"name": "John",
"age": 30,
"city": "New York"
}
# Use indentation, sort keys alphabetically, and custom separators
json_string = json.dumps(data, indent=4, sort_keys=True, separators=(",", " = "))
print(json_string)
The output will be formatted like this:
{
"age" = 30,
"city" = "New York",
"name" = "John"
}
Note that the separators argument is set to (“,”, ” = “), which means that the keys and values are separated by a comma and an equals sign, respectively.
The sort_keys argument is set to True, which means that the keys are sorted alphabetically.
The indent argument is set to 4, which means that the JSON object is indented with four spaces per level. Also you can use the json.JSONEncoder class to create a custom encoder that can be used to format the JSON output.
You can subclass the JSONEncoder class and override its default() method to handle custom objects that are not serializable by default.
Here’s an example that demonstrates how to create a custom encoder:
import json
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
class PersonEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, Person):
return {
"name": obj.name,
"age": obj.age
}
return json.JSONEncoder.default(self, obj)
person = Person("John", 30)
# Use the custom encoder to format the JSON output
json_string = json.dumps(person, cls=PersonEncoder)
print(json_string)
The output will be:
{"name": "John", "age": 30}
In this example, we defined a Person class and a custom encoder PersonEncoder.
The default() method of PersonEncoder checks if the object being serialized is an instance of the Person class. If it is, the default() method returns a dictionary with the name and age attributes of the Person object.
If it is not, the default() method calls the base class’s implementation of default() to handle the object.
When we call json.dumps() with the person object and the PersonEncoder class, the PersonEncoder class is used to format the JSON output.
Here are some examples of arguments that can be used to format the JSON
This argument is used to specify the number of spaces to use for indentation. It is commonly set to 2 or 4 spaces.
For example:
import json
data = {
"name": "John",
"age": 30,
"city": "New York"
}
json_string = json.dumps(data, indent=4)
print(json_string)
Output:
{
"name": "John",
"age": 30,
"city": "New York"
}
This argument is used to specify whether to sort the keys of the dictionary in the JSON output. By default, the keys are not sorted.
For example:
import json
data = {
"name": "John",
"age": 30,
"city": "New York"
}
json_string = json.dumps(data, sort_keys=True)
print(json_string)
Output:
{"age": 30, "city": "New York", "name": "John"}
This argument is used to specify whether to escape non-ASCII characters in the JSON output. By default, non-ASCII characters are escaped.
For example:
import json data = { “name”: “John”, “age”: 30, “city”: “Paris”, “emoji”: “” } json_string = json.dumps(data, ensure_ascii=False) print(json_string)🐍
Output:
{"name": "John", "age": 30, "city": "Paris", "emoji": "🐍"}
In this example, the ensure_ascii
argument is set to False
, which means that the “emoji” key with the snake emoji is not escaped.
This argument is used to specify the separators used to separate items in the JSON output. By default, a comma (“,”) and a colon (“:”) are used to separate items. For example:
import json
data = {
"name": "Omar",
"age": 17,
"city": "Cairo"
}
json_string = json.dumps(data, separators=(",", ":"))
print(json_string)
Output:
{"name":"Omar","age":17,"city":"Cairo"}
In this example, the separators argument is set to (“,”, “:”), which means that a comma (“,”) is used to separate items in the JSON output, and a colon (“:”) is used to separate keys and values.
This argument is used to specify whether to skip non-serializable keys in the dictionary. By default, non-serializable keys raise a TypeError exception.
For example:
import json
data = {
"name": "Omar",
"age": 17,
"city": "Cairo",
42: "answer"
}
json_string = json.dumps(data, skipkeys=True)
print(json_string)
Output:
{"name": "Omar", "age": 17 "city": "Cairo"}
In this example, the key 42 is not serializable, but it is skipped because the skipkeys argument is set to True.
This argument is used to specify a function that can convert non-serializable types into serializable types.
For example:
import json
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def person_encoder(obj):
if isinstance(obj, Person):
return {"name": obj.name, "age": obj.age}
else:
raise TypeError("Object of type 'Person' is not JSON serializable")
data = {
"name": "Omar",
"age": 17,
"city": "Cairo",
"person": Person("Gogo", 25)
}
json_string = json.dumps(data, default=person_encoder)
print(json_string)
Output:
{"name": "Omar", "age": 17, "city": "Cairo", "person": {"name": "Gogo", "age": 25}}
In this example:
1-The default argument is set to a function person_encoder that converts Person objects into dictionaries.
2-The Person object in the data dictionary is then serialized into a dictionary by the person_encoder function.
3-How to Order the Result? By default, the keys in a dictionary are serialized in the order in which they were created.
However, you can also specify a custom order for the keys using the sort_keys argument.
Here’s an example:
import json
data = {
"name": "Omar",
"age": 17,
"city": "Cairo"
}
key_order = ["age", "name", "city"]
json_string = json.dumps(data, sort_keys=True, key=lambda k: key_order.index(k) if k in key_order else len(key_order))
print(json_string)
Output:
{"age": 17, "name": "Omar", "city": "Cairo"}
In this example:
1-we’re using the key argument to provide a custom key function that first checks if the key is present in key_order.
2-If it is, we return its index in the list; otherwise, we return the length of the list, which will cause the key to be sorted last.
Note that this technique only works for dictionaries with a fixed set of keys. If your dictionary can have arbitrary keys, you should either use the default ordering or sort the keys alphabetically.
1.What does JSON stand for?
a. JavaScript Object Notation b. Java Serialization Object Network c. JavaScript Object Naming
Answer: a. JavaScript Object Notation
2.Which of the following data types can be represented in JSON?
a. strings b. numbers c. booleans d. all of the above
Answer: d. all of the above
3.Which Python module is used for working with JSON?
a. json b. pyjson c. js d. none of the above
Answer: a. json
4.Which method is used to convert a Python object to a JSON string?
a. json.load() b. json.loads() c. json.dump() d. json.dumps()
Answer: d. json.dumps()
5.How are keys and values separated in a JSON object?
a. with a comma (,) b. with a colon (:) c. with a semicolon (;) d. with a hyphen (-)
Answer: b. with a colon (:)
6.What is the maximum size of a JSON object?
a. 10 MB b. 100 MB c. 1 GB d. There is no maximum size limit for a JSON object.
Answer: d. There is no maximum size limit for a JSON object.
7.Which of the following programming languages natively supports JSON?
a. Python b. Java c. JavaScript d. All of the above
Answer: d. All of the above
8.What is the difference between JSON and XML?
a. JSON is more verbose than XML. b. JSON supports only string and number data types, while XML supports more data types. c. JSON is easier to read and write than XML. d. There is no difference between JSON and XML.
Answer: c. JSON is easier to read and write than XML.
9.What is the purpose of the json.loads()
method in Python?
a. To load a JSON file from disk. b. To convert a JSON string to a Python object. c. To convert a Python object to a JSON string. d. To write a Python object to a JSON file.
Answer: b. To convert a JSON string to a Python object.
10.Which of the following is a valid JSON object?
a. {“name”: “John”, “age”: 30, “is_married”: True} b. {“name”: “John”, “age”: 30, is_married: true} c. {“name”: “John”, “age”: “30”, “is_married”: “true”} d. {“name”: “John”, “age”: 30, “is_married”: “yes”}
Answer: a. {“name”: “John”, “age”: 30, “is_married”: True}
1.What is the file extension for a JSON file?
a. .json b. .js c. .py d. .txt
Answer: a. .json
2.Which of the following is a valid JSON array?
a. [1, “apple”, {“name”: “John”}] b. (1, “apple”, {“name”: “John”}) c. {1, “apple”, {“name”: “John”}} d. [1, “apple”, {“name”: “John”},]
Answer: a. [1, “apple”, {“name”: “John”}]
3.Which of the following is not a legal value in JSON?
a. true b. false c. null d. undefined
Answer: d. undefined
4.What is the difference between JSON and JavaScript?
a. JSON is a subset of JavaScript. b. JSON is a superset of JavaScript. c. JSON and JavaScript are completely different and unrelated. d. None of the above.
Answer: a. JSON is a subset of JavaScript.
5.What is the purpose of the json.dump()
method in Python?
a. To load a JSON file from disk. b. To convert a JSON string to a Python object. c. To convert a Python object to a JSON string. d. To write a Python object to a JSON file.
Answer: d. To write a Python object to a JSON file.
6.Which of the following is a valid JSON object?
a. {“name”: “John”, age: 30} b. {“name”: “John”, “age”: 30} c. {“name”: “John”, age=30} d. {“name”, “John”, “age”, 30}
Answer: b. {“name”: “John”, “age”: 30}
7.Which of the following is a valid way to access a value in a JSON object using JavaScript?
a. obj(name) b. obj[“name”] c. obj.name d. All of the above
Answer: d. All of the above
8.Which of the following methods can be used to convert a JSON string to a JavaScript object?
a. JSON.parse() b. JSON.stringify() c. JSON.load() d. JSON.dump()
Answer: a. JSON.parse()
9.What is the difference between JSON and XML?
a. JSON is more readable and simpler to use than XML. b. JSON is more verbose and complex than XML. c. JSON and XML are completely different and unrelated. d. None of the above.
Answer: a. JSON is more readable and simpler to use than XML.
10.Which of the following is not a legal data type in JSON?
a. string b. number c. function d. boolean
Answer: c. function
5.Which of the following is not a valid JSON data type?
a. Number b. String c. Function d. Boolean
Answer: c. Function
6.Which of the following is the correct syntax for a JSON array?
a. {“fruit”: [“apple”, “banana”, “orange”]} b. {“fruit”: “apple”, “banana”, “orange”} c. {“fruit”: “apple, banana, orange”} d. {“fruit”: [“apple”, “banana”, “orange”]
Answer: d. {“fruit”: [“apple”, “banana”, “orange”]}
7.Which method is used to convert a Python object into a JSON string?
a. json.dumps() b. json.loads() c. json.parse() d. json.stringify()
Answer: a. json.dumps()
8.Which symbol is used to separate name-value pairs in a JSON object?
a. : b. = c. , d. ;
Answer: a. :
9.Which of the following is a correct way to access a value in a JSON object in Python?
a. data{“name”} b. data[“name”] c. data.name d. data.get(“name”)
Answer: b. data[“name”]
a. Number b. String c. Function d. Boolean
Answer: c. Function
10.Which of the following is the correct syntax for a JSON array?
a. {“fruit”: [“apple”, “banana”, “orange”]} b. {“fruit”: “apple”, “banana”, “orange”} c. {“fruit”: “apple, banana, orange”} d. {“fruit”: [“apple”, “banana”, “orange”]}
Answer: d. {“fruit”: [“apple”, “banana”, “orange”]}
11.Which method is used to convert a Python object into a JSON string?
a. json.dumps() b. json.loads() c. json.parse() d. json.stringify()
Answer: a. json.dumps()
12.Which symbol is used to separate name-value pairs in a JSON object?
a. : b. = c. , d. ;
Answer: a. :
13.Which of the following is a correct way to access a value in a JSON object in Python?
a. data{“name”} b. data[“name”] c. data.name d. data.get(“name”)
Answer: b. data[“name”]
14.Which of the following methods can be used to parse a JSON string into a Python object?
a. json.dumps() b. json.loads() c. json.parse() d. json.stringify()
Answer: b. json.loads()
15.Which of the following is the correct way to represent a null value in JSON?
a. null b. None c. “null” d. “None”
Answer: a. null
16.Which of the following is an example of a JSON object?
a. {“name”: “John”, “age”: 30} b. [“apple”, “banana”, “orange”] c. “Hello, world!” d. 42
Answer: a. {“name”: “John”, “age”: 30}
17.Which of the following is an example of a JSON array?
a. {“name”: “John”, “age”: 30} b. [“apple”, “banana”, “orange”] c. “Hello, world!” d. 42
Answer: b. [“apple”, “banana”, “orange”]
18.Which of the following is not a valid way to represent a string value in JSON?
a. “Hello, world!” b. ‘Hello, world!’ c. Hello, world! d. “He said, “Hello!””
Answer: c. Hello, world! (strings in JSON must be enclosed in double quotes)