简体   繁体   English

jq替换json中部分值

[英]jq replace part of value in json

I need to replace part of a value from a json output and i could easily do this using sed -i however it would also replace other parts of the file i dont want it to, unless im missing something. 我需要从json输出中替换值的一部分,并且我可以使用sed -i轻松地做到这一点,但是它也将替换文件中我不希望的其他部分,除非即时消息丢失了。 The out put is { "LastModified": "2018-03-07T17:24:33.000Z", "Key": "pending/archive/f7ab1684-e94d-483e-ace1-560367c1196c_1000_s.json" } 输出是{ "LastModified": "2018-03-07T17:24:33.000Z", "Key": "pending/archive/f7ab1684-e94d-483e-ace1-560367c1196c_1000_s.json" }

and I need to replace the dash "-" on the LastModified value to a slash, then remove some stuff too like the "T" and the ".000Z" So i can eventually convert that timestamp to epoch. 我需要将LastModified值上的破折号“-”替换为斜杠,然后删除一些内容,例如“ T”和“ .000Z”,以便最终将时间戳转换为纪元。

I tried using cat list | 我尝试过使用猫清单| jq -r '.[] | jq -r'。[] | select (.LastModified == "-") .LastModified = "/"' and |= operator but i cant find anywhere else on the web that this has been accomplished. 选择(.LastModified ==“-”).LastModified =“ /”'和| =运算符,但我在网络上找不到其他已完成的操作。

With jq 's sub() and fromdate() functions: 使用jqsub()fromdate()函数:

jq '.LastModified |= (sub("\\.000Z";"Z") | fromdate)' input.json

The output: 输出:

{
  "LastModified": 1520443473,
  "Key": "pending/archive/f7ab1684-e94d-483e-ace1-560367c1196c_1000_s.json"
}

If your platform supports it, you could use the date functions to parse out then reformat the date string. 如果您的平台支持它,则可以使用date函数进行解析,然后重新格式化日期字符串。

.LastModified |= (sub("\\.000Z$"; "Z") | fromdateiso8601 | strftime("%Y/%m/%d %H:%M:%S"))

Otherwise, you could use the usual string manipulation techniques. 否则,您可以使用通常的字符串操作技术。

.LastModified |= "\(.[:10] | sub("-"; "/"; "g")) \(.[11:19])"

Both results in the results: 两者都导致结果:

{
  "LastModified": "2018/03/07 17:24:33",
  "Key": "pending/archive/f7ab1684-e94d-483e-ace1-560367c1196c_1000_s.json"
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM