格式化 json 文件以添加另一个字段

Formatting a json file to add another field

我有一个 json 格式的文件 below.I 想修改该文件以便向其添加另一个键值对。键应该是 url,值应该是从下面给出的消息中提取的 www.mywebsite.co.nz。执行此操作的简单方法是什么?

{"  
Timestamp":"Mon Mar 16 21:37:22 EDT 2015","Event":"Reporting  Time","Message":"load for http://xxx.xx.xx.xx:1xxxx/operations&proxy=www.mywebsite.co.nz&send=https://xxx.xx.xx.xx:xxxx/operations?event took 9426 ms (X Time: 306 ms, Y Time: 1923 ms)
StatusCode: Unknown<br>Cookies: nzh_weatherlocation=12; dax_ppv=11|NZH:home|NZH:home|NZH:home|9|undefined; _ga=GA1.4.1415798036.1426208630; _gat=1<br>Links: 225<br>Images: 24<br>Forms: 10<br>Browser: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/41.0.2272.76 Chrome/41.0.2272.76 Safari/537.36<br>CPUs: 2<br>Language: en-GB","UserInfo":"Reporting Time"}

作为 jqsed 的组合:

jq ".url = \"$(jq '.Message' input.json | sed 's/.*proxy=\([^&]*\).*//')\"" input.json > output.json

这包括三个步骤:

jq '.Message' input.json

从输入中提取消息部分 JSON,

sed 's/.*proxy=\([^&]*\).*//'

从邮件中提取域名,

jq ".url = \"domainname\"" input.json > output.json

将输入json的.url属性设置为提取的域名,将结果写入output.json.

我不得不指出,顺便说一句,域名本身在技术上并不是 URL,因此您可能需要重新考虑该属性名称。

对于 perl 用户,使用 ojo:

perl -Mojo -E '$j=j(b("input.file")->slurp);if($j->{Message}=~m/proxy=(.*?)&/){$j->{url}=;say j($j)}'

分解:

  • b()->slurp - 读取 input.file
  • j() - 将 json 转换为 perl 数据
  • 如果 Message 包含 "proxy=site&" - 获取站点
  • 添加到数据 url => site
  • j() 转换为 json 字符串
  • 并打印出来。