【问题标题】:Cannot index string : Wrong command with jq?无法索引字符串:jq 的命令错误?
【发布时间】:2023-04-04 16:01:01
【问题描述】:

我有这种类型的数据:

[
  "foo1:         xxxxxx",
  "foo2:    xxxxxx",
  "foo3:     xxxxxx",
  "foo4:         xxxxxx",
  "foo5:   xxxxxx",
  "foo6:       xxxxxx"
]

我想用 jq 解析它。我试过了:

cat file.txt | jq '.foo1'
cat file.txt | jq '.[] | .foo1'

而且我每次都有这个错误:

jq: error (at <stdin>:8): Cannot index string with string "foo1"
exit status 5

但我不知道为什么!

有人告诉我我的 jq 命令有什么问题吗?

谢谢

【问题讨论】:

  • 欢迎来到 SO。请根据minimal reproducible example 准则显示预期输出。
  • 你有一个文字字符串数组,不能像地图一样检索

标签: json parsing jq


【解决方案1】:

您提供的输入是一个字符串数组。命令.foo1 试图获取输入对象的foo1 字段,但输入是数组,而不是对象。同样,命令.[] | .foo1 正在尝试遍历输入数组(这很好),然后获取每个项目对象的foo1 字段,但这些项目是字符串,而不是对象。

如果您想获取以foo1: 开头的字符串中的xxxxxx,您可以执行以下操作:

$ jq '.[] | select(startswith("foo1")) | sub("foo1:\\s+"; "")' file.txt
"xxxxxx"

如果你想把你的输入变成一个实际的 JSON 对象,你可以遍历每个字符串,使用 capture 获取键和值,然后使用 from_entries 将它们全部拼接成一个对象.此时,您可以附加您原来的.foo1,您将获得您最初预期的行为。

$ jq 'map(capture("^(?<key>.*):\\s*(?<value>.*)$")) | from_entries' file.txt
{
  "foo1": "xxxxxx",
  "foo2": "xxxxxx",
  "foo3": "xxxxxx",
  "foo4": "xxxxxx",
  "foo5": "xxxxxx",
  "foo6": "xxxxxx"
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-02
    • 2021-03-15
    • 1970-01-01
    • 1970-01-01
    • 2016-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多