Understanding JSON Data Format and Python Processing Techniques
JSON (JavaScript Object Notasion) is a lightweight data interchange format that is language- and platform-independent, with parsers and libraries available for various programming languages. Its self-descriptive nature makes it easy to understand, and it is common used as the data format for API responses, making knowledge of JSON essential for interface testing.
JSON syntax follows specific rules: data is organized in key/value pairs, separated by commmas, with objects enclosed in curly braces {} and arrays in square brackets []. A key/value pair is written as key:value, such as "Name": "xiaomi".
JSON values can include:
- Numbers (integers or floating-point)
- Strings (enclosed in double quotes)
- Boolean values (true or false)
- Arrays (with in square brackets)
- Objects (within curly braces)
- null
Examples of JSON data types:
- JSON number: "status_code": 200
- JSON string: "Name": "xiaomi"
- JSON boolean: "result": true
- JSON array: "user": ["xiaomi", "pingguo", "xueli"]
- JSON object: { "firstName": "xiaomi", "lastName": "xueli" } In interface testing, JSON objects are typically returned.
JSON supports nested structures, such as arrays containing multiple objects. For instance: { "employees": [ { "firstName": "xiaomi", "lastName": "Doe" }, { "firstName": "Anna", "lastName": "Smith" }, { "firstName": "Peter", "lastName": "Jones" } ] } In this example, the "emplyoees" object is an array with three objects, each representing a record with first and last names.
In Python, the json module provides methods for encoding and decoding JSON data:
- json.dumps(): Converts Python data to a JSON string
- json.loads(): Converts a JSON string to Python data
Example of json.dumps():
import json
sample_data = {'user_id': 1, 'username': 'huang', 'passcode': '12345'}
print(type(sample_data))
json_string = json.dumps(sample_data)
print(type(json_string))
print(json_string)
Output:
<class 'dict'> <class 'str'> {"passcode": "12345", "user_id": 1, "username": "huang"}
Example of json.loads():
import json
json_string = '{"user_id": 1, "username": "huang", "passcode": "12345"}'
parsed_data = json.loads(json_string)
print(type(json_string))
print(type(parsed_data))
print(parsed_data)
print(parsed_data['user_id'])
print(parsed_data['username'])
Output:
<class 'str'> <class 'dict'> {'username': 'huang', 'passcode': '12345', 'user_id': 1}
1
huang
For file operations, JSON data can be written to or read from files:
# Write JSON data to a file
with open('output.json', 'w') as file:
json.dump(sample_data, file)
# Read JSON data from a file
with open('output.json', 'r') as file:
loaded_data = json.load(file)