2016-06-08 70 views
9

我正在使用jq來改寫我的JSONJSON中的Concat 2字段使用jq

JSON字符串:

{"channel": "youtube", "profile_type": "video", "member_key": "hello"}

通緝輸出:

{"channel" : "profile_type.youtube"}

我的命令:

echo '{"channel": "youtube", "profile_type": "video", "member_key": "hello"}' | jq -c '. | {channel: .profile_type + "." + .member_key}' 

我知道下面的命令會將字符串。但它不是在同一個邏輯工作如上:

echo '{"channel": "youtube", "profile_type": "video", "member_key": "hello"}' | jq -c '.profile_type + "." + .member_key' 

怎麼能只用JQ我實現我的結果?

+0

我想我要做的正好與我的YouTube API腳本同樣的事情;) –

回答

15

使用在你的字符串連接代碼括號:

echo '{"channel": "youtube", "profile_type": "video", "member_key": "hello"}' | jq '{channel: (.profile_type + "." + .channel)}' 
+0

考慮使用字符串插值來代替,那麼多個字符串連接更加清潔。 –

3

下面是一個使用字符串插值Jeff提出了一個解決方案:

{channel: "\(.profile_type).\(.member_key)"} 

例如

$ jq '{channel: "\(.profile_type).\(.member_key)"}' <<EOF 
> {"channel": "youtube", "profile_type": "video", "member_key": "hello"} 
> EOF 
{ 
    "channel": "video.hello" 
}