The full name of JSON is "JavaScript Object Notation"
, translated as "JavaScript Object Notation" or "JavaScript Object" Notation" is a lightweight, text-based, open data exchange format. JSON plays a vital role in the field of web development. If you want to show your skills in the field of web development, you must understand JSON. In layman's terms, Json is a text format commonly used for data storage.
The basic structure is key: value
, the key can only be string
, and the value can be a string, list, number, or other key Value pair .
The following data shows the different forms of Json structure very well:
{ "max": 1, "1": { "user": 825882638, "type": "image" "title": "超人" }, "a": [ "芝麻开门", { "a": 2 }, "b" ], "c": { "d": 888 "g": 888 } }
Note: The outermost layer of all Json text must have {}
Next, we will use the above Json text as a model to explain the parsing of Json files.
In Python, if we want to parse Json files, we must first import the json
library that comes with Python installation, that is, import json
, and then we can proceed. json operation.
The following code tells us how to read a json file
with open("./new.json", "r", encoding="utf-8") as f: content = json.load(f)
json.load reads json directly from the file Text, while json.loads reads json-encoded text rather than local files.
The above code reads json data from the "new.json" file in the current directory, and then the json.load
method will convert the read json text into Python The dictionary is stored in the content variable. Operating JSON format data in Python is actually operating on combined data types composed of dictionaries and lists.
For example, if we now want to extract the value of the bottom "d" (position 1 in the code) from the above json text, we can do this: val=content["c"]["d"] , so that the value of d
can be obtained, which is 333
. In addition to the above example, we can also see the list of [] packages. If we want to get the value of "a" (position 2 in the code), we should write like this: val=content["a"][ 1]["a"], at this time the value of val is 2
.
with open("./new.json", "w", encoding="utf-8") as f: json.dump(data, f, indent=4, ensure_ascii=False)
The above code is used to write data
data to the json file, in which the dump
method has many parameters , here we only talk about three of the above codes, please check the others by yourself.
obj
: The first parameter above is used to pass in the data that needs to be written into the Json file.
fp
: The second parameter above is used to pass in the text pointer that needs to be written into Json data
indent
: Pass in Json The amount of file newline indentation, usually 2 or 4.
ensure_ascii
: Whether to allow Ascii code. If it is True
(default), all input Chinese characters will be converted into \uXXXX and stored.
The code comes from a big guy on github. The code comments give detailed instructions on how to use it!
import json, os class JsonUtils(): relative_url = "./data/" abstract_url = "file:///home/ubuntu/qqbot/data/rpg/" @staticmethod def __preBuildFile(file: str, *default: Union[str, dict]) -> bool: """ 判断文件及路径是否存在,若不存在则创建并生成对应文件内容 :param file: 文件路径 :param default: 默认文件内容 :return: """ if (not os.path.exists(file)): path = os.path.split(file) if (not os.path.exists(path[0])): os.mkdir(path[0]) with open(file, "w", encoding=utf-8") as f: if (default): arg = default[0] if (isinstance(arg, str)): f.write(arg) elif (isinstance(arg, dict)): try: js = json.dumps(arg, indent=4, ensure_ascii=False) f.write(js) except json.JSONEncoder: return False else: f.write(str(arg)) else: f.write("") return True @classmethod async def read(cls, filename: str, *default) -> Tuple[dict, bool]: """ 读取指定json文件 :param filename: 文件路径 :param default: 若无此文件,创建该文件时写入的内容 :return: [读取到的内容, 是否为新创建的文件] """ file_url = cls.relative_url + filename if (default): res = JsonUtils.__preBuildFile(file_url, default[0]) else: res = JsonUtils.__preBuildFile(file_url) with open(file_url, "r", encoding="utf-8") as f: content = json.load(f) return (content, res) @classmethod async def write(cls, filename: str, data: dict) -> None: """ 写入Json数据 :param filename: 文件路径 :param data: 写入的数据 :return: """ file_url = cls.relative_url + filename JsonUtils.__preBuildFile(file_url) with open(file_url, "w", encoding="utf-8") as f: content = json.dumps(data, indent=4, ensure_ascii=False) f.write(content)
The above is the detailed content of How to read and write JSON format data in Python. For more information, please follow other related articles on the PHP Chinese website!