在 jq 中处理 json 的字符串表示

Processing string representation of json within jq

我在 bash psql_json() 中有一个函数可以访问 postgres 数据库并且 return 是 json。我无法编辑此 bash 函数,但它会在此查询中注入一个 postgres 语句,然后将其发送到 db:

"select row_to_json(t)::json from ($arg) t;"

其中 arg 是一些语句,即:

select * from table

但是,此函数 return 是一个格式奇怪的 json 字符串,如下所示:

{\"id\":1,\"firstName\":\"firstName1\",\"lastName\":\"lastName1\"}\n
{\"id\":2,\"firstName\":\"firstName2\",\"lastName\":\"lastName2\"}

上面的输出是在 运行 这些语句之后发生的:

local_fn="$(mktemp)"
psql_json 'select * from table' > "$local_fn"
cat "$local_fn"

现在,当我尝试将 json 按原样放入 jq 时,出现以下错误:

cat json1.json | jq '.'

jq: error: syntax error, unexpected $end, expecting ';' or ')' (Unix shell quoting issues?)

这似乎表明问题是我将一个字符串传递给它不喜欢并且无法解析的 jq,所以我尝试了两个:

cat json1.json | jq 'fromjson]'
cat json1.json | jq '[.[]|fromjson]'

他们俩return

parse error: Invalid numeric literal at line 1, column 3

有什么方法可以以干净的方式将上面 json 的字符串表示形式放入 jq 中进行处理,或者我是否需要 clean/edit bash 中的字符串?

您可以使用 jq 或 text-processing 工具修复输入,例如 :

< weird.json jq -R 'sub("^";"\"") | sub("$";"\"") | fromjson | fromjson'

< weird.json sed -e 's/^/"/' -e 's/$/"/' | jq -R 'fromjson|fromjson'

根据您的输入,两种情况下的结果都是:

{
  "id": 1,
  "firstName": "firstName1",
  "lastName": "lastName1"
}
{
  "id": 2,
  "firstName": "firstName2",
  "lastName": "lastName2"
}