机器人开发中的全局路径规划:A*与Dijkstra算法深度解析
2026/9/12 15:59:02
Jsonnet 是一种领域特定语言(DSL),用于以结构化、可编程的方式生成JSON(以及兼容格式如 YAML、TOML)。它由 Google 开发,旨在解决纯 JSON 在配置管理、模板复用和逻辑表达方面的不足。
+:、::、+::等操作符)、隐藏字段(::为私有)、局部作用域(local)。std库,提供字符串处理、数组/对象操作、数学函数等。local name = "alice"; { user: name, id: 1001 }local greeting(person) = "Hello, " + person + "!"; { message: greeting("Bob") }local env = "prod"; { db_url: if env == "prod" then "db.prod.example.com" else "db.dev.example.com" }local baseConfig = { port: 8080, timeout: 30, debug:: false // 私有字段,不会出现在最终 JSON 中 }; { dev: baseConfig { port: 8081, debug:: true } }local services = ["web", "api", "db"]; { containers: [ { name: s, image: s + ":latest" } for s in services ] }std.manifestJsonEx、std.manifestYamlDoc等函数输出所需格式# macOS (Homebrew)brewinstalljsonnet# Linux (Debian/Ubuntu)sudoapt-getinstalljsonnet# 或从源码编译(Go 实现:go-jsonnet,性能更好)goinstallgithub.com/google/go-jsonnet/cmd/jsonnet@latest# 生成 JSONjsonnet config.jsonnet# 生成 YAMLjsonnet --yaml-stream config.jsonnet# 格式化jsonnetfmt -i config.jsonnetadd_custom_command)中调用jsonnet生成配置import "file.libsonnet"复用代码std.map,std.filter,std.toString,std.base64,std.parseJson等error "message"抛出错误"Port is %d" % portstd.manifestText或自定义模板示例:生成 YAML 配置
local cfg = { apiVersion: "v1", kind: "ConfigMap", metadata: { name: "app-config" }, data: { ENV: "production", LOG_LEVEL: "info" } }; std.manifestYamlDoc(cfg) // 注意:需用 `jsonnet --yaml-stream`Jsonnet 是一种功能强大的结构化配置语言,它扩展了 JSON,提供了模块化、可重用性和表达能力,广泛用于配置管理、Kubernetes 清单生成等场景。以下是 Jsonnet 的几个高级概念,特别针对你关心的文件包含和注释功能:
Jsonnet 支持通过import和importstr机制包含其他文件,实现模块化和配置复用。
import "file.jsonnet"
导入另一个 Jsonnet 文件,并将其求值结果作为表达式使用(通常是对象或函数)。
// config.libsonnet { commonPort: 8080, server(name): { name: name, port: $.commonPort } } // main.jsonnet local lib = import "config.libsonnet"; { api: lib.server("api"), web: lib.server("web") }importstr "file.txt"
以原始字符串形式导入文件内容(不解析为 Jsonnet),常用于嵌入模板、脚本或非结构化文本。
local script = importstr "init.sh"; { initScript: script }Jsonnet 的 import 路径是相对于当前文件的,也支持通过
-J或--jpath指定额外的搜索路径。
Jsonnet 完全支持类似 C/C++ 的注释语法:
// This is a comment/* This is a multi-line comment */这些注释在 Jsonnet 被编译为 JSON 后会自动被剥离,不会出现在输出中,因此不影响最终 JSON 的合法性。
{ // 服务端口配置 port: 8080, /* 启用调试模式? 仅在开发环境使用 */ debug: false }⚠️ 注意:原始 JSON 不支持注释,但 Jsonnet 作为超集语言,允许在源码中使用注释,这是它优于纯 JSON 的一大优势。
| 特性 | 说明 |
|---|---|
| 函数(Functions) | 支持具名/匿名函数,实现参数化配置 |
| 继承与合并(+:、+: super) | 支持对象继承、字段覆盖、递归合并 |
| 条件表达式 | if/then/else可用于动态生成结构 |
| 列表/对象推导 | 类似 Python 的列表推导式,用于生成复杂结构 |
| 标准库 | 内置std库,提供字符串处理、数学、时间、YAML/JSON 转换等 |