中文 | English
API: wingman.json
JSON parsing and serialization module.
Module Overview
The json module provides parsing and serialization for the JSON format:
- Parse JSON - convert a JSON string into a native object
- Serialize JSON - convert a native object into a JSON string
- Formatted output - pretty output with indentation control
Python's None and Lua's nil serialize to JSON null through encode.
Parse a JSON String
decode(str) / decode(str)
Description: Parses a JSON string and converts it into a native object.
Signature:
python
decode(str: str) -> Anylua
decode(str: string) -> anyParameters:
str- a string in JSON format
Returns:
- Python: the parsed value (
dict/list/str/int/float/bool/None) - Lua: the parsed value (
table/string/number/boolean/nil)
On parse failure:
- Returns
None(Python) /nil(Lua); no exception is thrown - Note: because JSON
nullitself also parses toNone/nil, the return value alone cannot distinguish "the parsed result is null" from "parsing failed"
python
from wingman import json
# 解析 JSON 字符串
data = json.decode('{"name": "Player1", "score": 100}')
print(data['name']) # "Player1"
print(data['score']) # 100
# 解析数组
items = json.decode('["sword", "shield", "potion"]')
for item in items:
print(item)Serialize to a JSON String
encode(value, indent?) / encode(value, indent?)
Description: Serializes a native object into a JSON string.
Signature:
python
encode(value: Any, indent: int = -1) -> strlua
encode(value: any, indent: number = -1) -> stringParameters:
value- the value to serialize (dict, list, or JSON-compatible types)indent- optional, number of indent spaces-1or omitted: compact format (no spaces)0or any other value: indent with the given number of spaces
Returns:
- a string in JSON format
python
from wingman import json
obj = {
"name": "Player1",
"score": 100,
"items": ["sword", "shield"]
}
# 压缩格式
compressed = json.encode(obj)
# {"name":"Player1","score":100,"items":["sword","shield"]}
# 格式化,2 空格缩进(模块函数只接受位置参数)
formatted = json.encode(obj, 2)
print(formatted)Available Interfaces
| Python Function | Lua Function | Description | Parameters |
|---|---|---|---|
decode(str) | decode(str) | Parse a JSON string | str: JSON string Returns: native object; None/nil on parse failure |
encode(value, indent?) | encode(value, indent?) | Serialize to JSON | value: native object indent: number of indent spaces (default -1 = compact) Returns: JSON string |