注意:该中文文档为社区驱动的非官网文档,可能存在错译、漏译或过时等问题,请以官网文档 Documentation 为准,如发现错漏,也欢迎 您的贡献镜像)。Typst 非官方中文交流 QQ 群:793548390
Warning: the Chinese document is a community-driven non-official document, there may be mistranslation, omission or outdated problems, please refer to the official website documentation.
Typst 中文文档

json

从 JSON 文件读取结构化数据。

文件必须包含有效的 JSON 对象或数组。 JSON 对象将被转换为 Typst 字典,JSON 数组将转换为 Typst 数组。 字符串和布尔值将被转换为相应的 Typst 类型值。 null 将被转换为 none。 数字将根据是否为整数转化为浮点值或整数值。

该函数将返回一个字典或一个数组,这具体取决于读取的 JSON 文件。

示例中的 JSON 文件为一个包含 temperatureunitweather 键值的对象。

举例

#let forecast(day) = block[
  #box(square(
    width: 2cm,
    inset: 8pt,
    fill: if day.weather == "sunny" {
      yellow
    } else {
      aqua
    },
    align(
      bottom + right,
      strong(day.weather),
    ),
  ))
  #h(6pt)
  #set text(22pt, baseline: -8pt)
  #day.temperature °#day.unit
]

#forecast(json("monday.json"))
#forecast(json("tuesday.json"))
Preview

参数
参数是函数的输入,它们在函数名称后面的括号中传入。

json() -> any

path
str
必需参数位置参数
位置参数按顺序传入,不带名称。

JSON 文件路径。

定义
函数和类型可以有与其关联的定义 (成员或方法)。可以使用 "." 操作符来访问调用它们。

decode

从 JSON 字符串/字节流中读取结构化数据。

json.decode() -> any

data
str bytes
必需参数位置参数
位置参数按顺序传入,不带名称。

JSON 数据。

encode

将结构化数据编码为 JSON 字符串。

json.encode() -> str

value
any
必需参数位置参数
位置参数按顺序传入,不带名称。

被编码的值。

pretty

是否使用换行和缩进格式化输出的 JSON 字符串。

默认:true