我需要帮助编写脚本来编辑file.json。以下是JSON文件:
{
"version" : "1.0",
"analytics" : {
"rsids" : "",
"charset" : "UTF-8",
"ssl" : false,
"offlineEnabled" : true,
"lifecycleTimeout" : 300,
"privacyDefault" : "optedin",
"poi" : []
},
"target" : {
"clientCode" : "",
"timeout" : 5
},
"audienceManager" : {
"server" : ""
}
}
我需要编辑上面的file.json并为rsids,客户端代码和服务器提供值。
答案 0 :(得分:1)
在Gnu Awk第4版中,您可以使用patsplit()
。请尝试以下bash脚本:
#! /bin/bash
IFS=$'\n' ar=( rsids="1 2" clientCode="2" server="3")
mv file.json file.json.bak
gawk -va="${ar[*]}" -f a.awk file.json.bak > file.json
其中a.awk
是:
BEGIN {
n=split(a,b,"\n")
for (i=1; i<=n; i++) {
split(b[i],z,"=")
w[("\""z[1]"\"")]=("\""z[2]"\"")
}
RS="^$" #Read whole file in a single record
}
{
n=patsplit($0,c,/"[^"]*"[[:blank:]]*:[[:blank:]]*"[^"]*"/,s1)
printf "%s", s1[0]
for (i=1; i<=n; i++) {
patsplit(c[i],d,/"[^"]*"/,s2)
if (d[1] in w)
d[2]=w[d[1]]
printf "%s%s%s%s%s%s",s2[0],d[1],s2[1],d[2],s2[2],s1[i]
}
}
输出:
{
"version" : "1.0",
"analytics" : {
"rsids" : "1 2",
"charset" : "UTF-8",
"ssl" : false,
"offlineEnabled" : true,
"lifecycleTimeout" : 300,
"privacyDefault" : "optedin",
"poi" : []
},
"target" : {
"clientCode" : "2",
"timeout" : 5
},
"audienceManager" : {
"server" : "3"
}
}
修改强>
如果您想使用命令行参数调用,请将脚本的第一行更改为:
IFS=$'\n' ar=( "$@" )
并称之为:
bash$ editJson rsids="1 2" clientCode="2" server="3"
答案 1 :(得分:1)
如果你有Ruby
require "rubygems"
require 'json'
parsed = JSON.parse( File.open("file.json").read )
puts parsed["analytics"]["rsids"]
puts parsed["target"]["clientCode"]