【问题标题】:sed to replace value for a key in a json objectsed 替换 json 对象中键的值
【发布时间】:2018-01-09 21:10:36
【问题描述】:

我想做什么?

给定一个 json 事件文件。我想通过关键字定位特定事件,然后用“”替换该事件中的键值。 这必须通过 sed 完成(Splunk 转发问题。我不会让您厌烦细节)。

示例事件

{
  "message":"we have a response from SomeService",
  "other":"some stuff",
  "other2":"some other stuff",
  "xml":"<Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:awsse=\"http://xml.chicken.com/2010/06/Session_v3\" xmlns:wsa=\"http://www.w3.org/2005/08/addressing\"><Header><To>http://www.w3.org/2005/08/addressing/anonymous</To><From><Address>..... AND SO ON BIG GIANT NASTEY XML",
  "other3":"even more stuff"
}

期望的结果

{
  "message":"we have a response from SomeService",
  "other":"some stuff",
  "other2":"some other stuff",
  "xml":"",
  "other3":"even more stuff"
}

我尝试了什么? 我可以隔离事件并更换钥匙没问题。我正在努力使用正则表达式来替换 json 中键的 value

cat test.json | sed '/"we have a response from SomeService"/ s/other2/chicken/'

谢谢你的帮助!

【问题讨论】:

  • 不,他们不是。整个json事件就是一行。
  • json和html是同一种语法,我们都知道that works
  • s/other2":"[^"]*",/other2":"newValue",/ ??将所有内容放在一条线上,贪婪的.* 会烧死你,所以请使用[^"]*,这意味着任意数量的非双引号字符。
  • 你可以试试这个cat test.json | sed '/"xml":/ s/"xml":[^,]*/"xml":""/' :)
  • Paul - 这很好用,你想把它作为答案发布,这样我就可以用绿色复选标记了吗?

标签: json regex sed replace


【解决方案1】:

从评论中复制

你可以试试这个

cat test.json | sed '/"xml":/ s/"xml":[^,]*/"xml":""/'

[^,]* 将匹配所有内容,直到找到 ,

【讨论】:

    猜你喜欢
    • 2015-04-22
    • 1970-01-01
    • 2020-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-23
    • 2021-08-22
    相关资源
    最近更新 更多