web-automation-demo/Library/Json.py

25 lines
830 B
Python
Raw Permalink Normal View History

2023-03-13 18:49:49 +08:00
import json
def json_encode(data, indent=None, unicode=True):
return json.dumps(data, indent=indent, ensure_ascii=unicode)
def json_decode(data):
return json.loads(data)
if __name__ == '__main__':
# e.g. The default does not indent, and the string will be coded by the unicode.
print(json_encode({"id": 101, "name": "汤姆", "friends": ["托尼", "杰森"]}))
# e.g. Indent 4 spaces.
print(json_encode({"id": 101, "name": "汤姆", "friends": ["托尼", "杰森"]}, indent=4))
# e.g. Indent 4 spaces and no coded by the unicode.
print(json_encode({"id": 101, "name": "汤姆", "friends": ["托尼", "杰森"]}, indent=4, unicode=False))
# e.g. Decode JSON data.
print(json_decode(
'''
{"id": 101, "name": "汤姆", "friends": ["托尼", "杰森"]}
'''
))