json.parse() 函数
json.parse() 是实验性的,随时可能更改。
json.parse() 接收JSON数据作为字节并返回一个值。
JSON类型转换为Flux类型如下:
| JSON类型 | Flux类型 |
|---|---|
| 布尔型 | 布尔型 |
| 数字 | 浮点数 |
| 字符串 | 字符串 |
| 数组 | 数组 |
| 对象 | 记录 |
函数类型签名
(data: bytes) => A
有关更多信息,请参见 Function type signatures。
参数
数据
(必填) 要解析的 JSON 数据(以字节形式)。
示例
解析和使用JSON数据重构表格
import "experimental/json"
data
|> map(
fn: (r) => {
jsonData = json.parse(data: bytes(v: r._value))
return {
_time: r._time,
_field: r._field,
a: jsonData.a,
b: jsonData.b,
c: jsonData.c,
}
},
)
解析 JSON 并使用数组函数将其转换为表格
import "experimental/json"
import "experimental/array"
jsonStr =
bytes(
v:
"{
\"node\": {
\"items\": [
{
\"id\": \"15612462\",
\"color\": \"red\",
\"states\": [
{
\"name\": \"ready\",
\"duration\": 10
},
{
\"name\": \"closed\",
\"duration\": 13
},
{
\"name\": \"pending\",
\"duration\": 3
}
]
},
{
\"id\": \"15612462\",
\"color\": \"blue\",
\"states\": [
{
\"name\": \"ready\",
\"duration\": 5
},
{
\"name\": \"closed\",
\"duration\": 0
},
{
\"name\": \"pending\",
\"duration\": 16
}
]
}
]
}
}",
)
data = json.parse(data: jsonStr)
// Map over all items in the JSON extracting
// the id, color and pending duration of each.
// Construct a table from the final records.
array.from(
rows:
data.node.items
|> array.map(
fn: (x) => {
pendingState =
x.states
|> array.filter(fn: (x) => x.name == "pending")
pendingDur =
if length(arr: pendingState) == 1 then
pendingState[0].duration
else
0.0
return {id: x.id, color: x.color, pendingDuration: pendingDur}
},
),
)