JSON Tokenizer
For lexical analysis of JSON, I mainly referred to the method in the screenshot above and wrote a simple example myself. It is relatively simple to write, and it should be said that it can only support a simple subset of JSON.
For the types of TOKEN here, refer to https://json.org, but its JSON syntax format is with whitespace. I am not used to dealing with this, so I did not refer to its syntax. After lexical analysis, spaces, newlines, and tabs are filtered out. I simply discard them without processing them.
json_tokenizer.py
Use regular expressions to perform lexical analysis of JSON.
import json import re from typing import Dict, List, Union # TOKEN 的种类 LEFT_BRACE = "LEFT_BRACE" # { RIGHT_BRACE = "RIGHT_BRACE" # } LEFT_BRACKET = "LEFT_BRACKET" # ] RIGHT_BRACKET = "RIGHT_BRACKET" # [ COLON = "COLON" # : COMMA = "COMMA" # , NUMBER = "NUMBER" # ".*?" STRING = "STRING" # [1-9]\d* BOOL = "BOOL" # true/false NULL = "NULL" # null NEWLINE = "NEWLINE" # \n SKIP = "SKIP" # ' ', '\t' MISMATCH = "MISMATCH" # mismatch # 处理 token 的正则 token_specification = [ ('LEFT_BRACE', r'[{]'), ('RIGHT_BRACE', r'[}]'), ('LEFT_BRACKET', r'[\[]'), ('RIGHT_BRACKET', r'[\]]'), ('COLON', r'[:]'), ('COMMA', r'[,]'), ('NUMBER', r'-?[1-9]+[0-9]*'), ('STRING', r'".*?"'), ('BOOL', r'(true)|(false)'), ('NULL', r'null'), ('NEWLINE', r'\n'), ('SKIP', r'[ \t]'), ('MISMATCH', r'.') ] tok_regex = '|'.join('(?P<%s>%s)' % pair for pair in token_specification) print("Debug: ", tok_regex) def process(kind: str, value: str) -> Dict[str, Union[str, bool, int, None]]: """ 处理输入的 kind 和 value,并生成 Dict 对象,简单表示 token 对象 """ if kind == STRING: # 去掉外层的双引号,暂时没有比较好的方式 return {"kind": kind, "value": value[1:-1]} if kind == NUMBER: return {"kind": kind, "value": int(value)} if kind == BOOL: if value == "true": return {"kind": kind, "value": True} else: return {"kind": kind, "value": False} if kind == NULL: return {"kind": kind, "value": None} return {"kind": kind, "value": value} def tokenizer(json_str: str) -> List[Dict[str, Union[str, bool, int, None]]]: """ tokenizer """ tokens = [] for m in re.finditer(tok_regex, json_str): # 获取 token 的类型 kind = m.lastgroup # 获取 token 的值 value = m.group() if kind == MISMATCH: raise Exception("json format is error") if kind == NEWLINE: continue if kind == SKIP: continue token = process(kind=kind, value=value) tokens.append(token) return tokens if __name__ == "__main__": json_doc = open("./demo.json", "r", encoding="utf-8").read() tokens = tokenizer(json_doc) if tokens: json.dump(tokens, open("./json_tokens.json", "w", encoding="utf-8"), ensure_ascii=False)
I have put all the input and output data in the document. I will post my input data and part of the output data below.
demo.json
{ "name": "小黑子", "age": 3, "gender": false, "other_info": { "friends": [ "嘎子", "潘叔", "狗" ], "declaration": "练习时长两年半", "hobbies": [ "唱", "跳", "rap", "篮球????" ] } }
json_token.json Part of the data. I formatted the data, so it is relatively long. Here is only a part.
JSON Parser
json_parser.py
Parser the token sequence generated in the previous step to generate a Dict object corresponding to JSON. The implementation of parser refers to the json syntax file of antlr4, which removes the whitespace and is simpler to process.
import json from typing import Dict, Union # TOKEN 的种类 LEFT_BRACE = "LEFT_BRACE" # { RIGHT_BRACE = "RIGHT_BRACE" # } LEFT_BRACKET = "LEFT_BRACKET" # ] RIGHT_BRACKET = "RIGHT_BRACKET" # [ COLON = "COLON" # : COMMA = "COMMA" # , NUMBER = "NUMBER" # ".*?" STRING = "STRING" # [1-9]\d* BOOL = "BOOL" # true/false NULL = "NULL" # null class Token(object): """为了简单,就不创建这个了""" class JSON_Parser(object): """ JSON_Parser the class aims parse input token sequence into a python object or array. """ def __init__(self, tokens) -> None: self.index = 0 self.tokens = tokens def get_token(self) -> Dict[str, Union[str, int, bool, None]]: """ get current's token """ if self.index < len(self.tokens): return self.tokens[self.index] else: raise Exception("index out of range.") def move_token(self) -> Dict[str, Union[str, int, bool, None]]: """ move to next token and return it """ if self.index + 1 < len(self.tokens): self.index = self.index + 1 return self.tokens[self.index] else: raise Exception("index out of range.") def parse(self): """ parse whole json """ token = self.get_token() if token.get("kind") == LEFT_BRACE: return self.parse_obj() elif token.get("kind") == LEFT_BRACKET: return self.parse_arr() else: raise Exception("error json, neither object or array.") def parse_obj(self): """ parse object """ obj = {} token = self.move_token() kind = token.get("kind") # '{' '}' if kind == RIGHT_BRACE: return obj # '{' pair (',' pair)* '}' name, val = self.parse_pair() obj[name] = val while self.index < len(self.tokens): token = self.move_token() kind = token.get("kind") if kind == COMMA: self.move_token() name, val = self.parse_pair() obj[name] = val elif kind == RIGHT_BRACE: return obj else: raise Exception("parse object encounter error") def parse_arr(self): """ parse array """ arr = [] token = self.move_token() kind = token.get("kind") # '[' ']' if kind == RIGHT_BRACE: return arr # '[' value (',' value)* ']' val = self.parse_value() arr.append(val) while self.index < len(self.tokens): token = self.move_token() kind = token.get("kind") if kind == COMMA: self.move_token() val = self.parse_value() arr.append(val) elif kind == RIGHT_BRACKET: return arr else: raise Exception("parse array encounter error") def parse_value(self): """ parse value """ token = self.get_token() kind = token.get("kind") if kind == LEFT_BRACE: return self.parse_obj() elif kind == LEFT_BRACKET: return self.parse_arr() elif kind == STRING or kind == NUMBER or kind == BOOL: return token.get("value") elif kind == NULL: return else: raise Exception("encounter unexcepted token") def parse_pair(self): """ parse pair """ token = self.get_token() kind = token.get("kind") name = token.get("value") # STRING ':' value if kind == STRING: token = self.move_token() kind = token.get("kind") if kind == COLON: token = self.move_token() return name, self.parse_value() raise Exception("parse pair encounter error") if __name__ == "__main__": # json token 文件路径 TOKEN_PATH = "./json_tokens.json" # 读取 token 序列 input_tokens = [token for token in json.load( open(TOKEN_PATH, "r", encoding="utf-8"))] if not input_tokens: raise Exception("input token sequence is empty") # 调试的时候,用来查表的,很方便定位到 index 走到哪一个 token 了 for i, tok in enumerate(input_tokens): print(f"debug {i:2d} --> {tok}") print("\n===========================================\n") parser = JSON_Parser(tokens=input_tokens) json_obj = parser.parse() # 再将 object 转成 json 并格式化后输出 print(json.dumps(json_obj, ensure_ascii=False, indent=4))
Output result:
The above is the detailed content of How to write a simple JSONParser using Python. For more information, please follow other related articles on the PHP Chinese website!

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version
Recommended: Win version, supports code prompts!

SublimeText3 Chinese version
Chinese version, very easy to use

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software