如何将JSON.stringify文件插入JSON消息?

时间:2016-12-15 03:48:14

标签: json command-line-interface jq

我在这里有一条SNS JSON消息:https://s.natalian.org/2016-12-15/sns-event.json

但是我需要使用Message字段作为JSON数据结构的有效负载。如何快速插入一段JSON,以便最终的JSON如下所示:https://s.natalian.org/2016-12-15/sns-event-stringified-message.json

"Message": "[{\"From\": \"foo\",\"To\": \"bar\"}]",

为了这个例子,要插入的file.json具有内容:

[
  {
    "From": "foo",
    "To": "bar"
  }
]

我目前正在手工处理JSON.stringify,这种错误容易出现大型结构。

2 个答案:

答案 0 :(得分:3)

将另一个文件作为参数文件读取,然后从文件中分配新的消息值。您可以使用tojson(或@json)获取当前对象的字符串版本。

$ jq --argfile file file.json '.Records[0].Sns.Message = ($file | tojson)' input.json

答案 1 :(得分:0)

这是一种稍微不同的方法,也更为一般。

假设我们想要为"消息"分配一个值。字段,无论它出现在何处(无论多久发生),都不必担心细节。

为了完全通用地执行此操作,这里有一个带有字段名称(JSON字符串)和所需值的函数:

def setall(key; value):
  walk(if type == "object" and has(key) then .[key] = value else . end);

(如果您的jq没有walk/1,其定义(如jq的builtin.jq中所示)将包含在下面。)

要解决原始问题,要使用的过滤器为:

setall( "Message"; $file|tojson )

其中$ file可以在命令行中定义,如下所示:

$ jq --argfile file file.json -f setall.jq input.json

这里假设所有jq位都放在名为setall.jq的文件中。

步行/ 1

# Apply f to composite entities recursively, and to atoms
def walk(f):
  . as $in
  | if type == "object" then
      reduce keys[] as $key
        ( {}; . + { ($key):  ($in[$key] | walk(f)) } ) | f
  elif type == "array" then map( walk(f) ) | f
  else f
  end;