YouTip LogoYouTip

Python3 Json

# Python3.x Python3 JSON Data Parsing JSON (JavaScript Object Notation) is a lightweight data interchange format. If you are not familiar with JSON, you can first read our (#). In Python3, the `json` module can be used to encode and decode JSON data. It contains two functions: * **json.dumps():** Encodes data. * **json.loads():** Decodes data. !(#) During the JSON encoding and decoding process, Python's native types and JSON types are converted to each other. The specific conversion mapping is as follows: ### Python Encoding to JSON Type Conversion Table: | Python | JSON | | --- | --- | | dict | object | | list, tuple | array | | str | string | | int, float, int- & float-derived Enums | number | | True | true | | False | false | | None | null | ### JSON Decoding to Python Type Conversion Table: | JSON | Python | | --- | --- | | object | dict | | array | list | | string | str | | number (int) | int | | number (real) | float | | true | True | | false | False | | null | None | ### json.dumps and json.loads Examples The following examples demonstrate converting Python data structures to JSON: ## Example (Python 3.0+) #!/usr/bin/python3 import json# Python dictionary type converted to JSON object data = { 'no' : 1, 'name' : 'Tutorial', 'url' : '' } json_str = json.dumps(data)print("Python original data:", repr(data))print("JSON object:", json_str) Executing the above code produces the following output: Python original data: {'no': 1, 'name': 'Tutorial', 'url': ''} JSON object: {"no": 1, "name": "Tutorial", "url": ""} From the output, it can be seen that simple types after encoding are very similar to their original `repr()` output. Continuing from the previous example, we can convert a JSON-encoded string back into a Python data structure: ## Example (Python 3.0+) #!/usr/bin/python3 import json# Python dictionary type converted to JSON object data1 = { 'no' : 1, 'name' : 'Tutorial', 'url' : '' } json_str = json.dumps(data1)print("Python original data:", repr(data1))print("JSON object:", json_str)# Convert JSON object to Python dictionary data2 = json.loads(json_str)print("data2['name']: ", data2['name'])print("data2['url']: ", data2['url']) Executing the above code produces the following output: Python original data: {'name': 'Tutorial', 'no': 1, 'url': ''} JSON object: {"name": "Tutorial", "no": 1, "url": ""} data2['name']: Tutorial data2['url']: If you are dealing with files instead of strings, you can use **json.dump()** and **json.load()** to encode and decode JSON data. For example: ## Example (Python 3.0+) # Write JSON data with open('data.json', 'w') as f: json.dump(data,
← Python3 Date TimePython3 Att Time Mktime Html β†’