1

I have a output of json format as below

{
"ip": "0.0.0.0",
"hostname": "No Hostname",
"city": "Beijing",
"region": "Beijing Shi",
"country": "CN",
"loc": "39.9289,116.3883",
"org": "AS55967 Beijing Baidu Netcom Science and Technology Co., Ltd."
}

i need values of country and city as below

CN        Beijing

i have used below jq command and sed command to display country but dont know how to display city as another column.

jq

 curl  -s ipinfo.io/0.0.0.0 | jq '.country'

sed

 curl  -s ipinfo.io/0.0.0.0 | sed '/country/!d' | sed s/\"country\":\ //g | sed 's/\"//g' | sed 's/\,//g'

The output of this country and city columns should be added to 4th & 5th column of another csv file sample below

2016-03-29 00:05:23 0.0.0.0 CN Beijing 10.0.0.197 
2016-03-29 00:56:37 1.1.1.1 FR France 10.0.1.117
2016-03-29 00:57:20 2.2.2.2 FR France 10.0.0.197
1
  • jq -j '.country, " ", .city, "\n"'? Then paste other_file jq_output? Commented Apr 5, 2016 at 14:48

3 Answers 3

2
curl  -s ipinfo.io/0.0.0.0 | jq -r '.country +"\t"+  .city'
Sign up to request clarification or add additional context in comments.

1 Comment

Consider using string interpolation instead. It'll be much cleaner.
1
$ cat tst.awk
BEGIN { FS="\": \""; OFS="\t" }
{ gsub(/^"|",$/,""); f[$1] = $2 }
/}/ { print f["country"], f["city"]; delete f }

$ awk -f tst.awk file
CN      Beijing

Since you didn't provide the "other file" to add the output of this to or provide any details on how you want to do that, it's not clear what you want to do with that so it's left to you...

1 Comment

Thanks Ed, it helped too
0

You can first put to two fields you're interested in into an array:

$ curl -s ipinfo.io | jq '[.country, .city]'
[
  "US",
  "Mountain View"
]

And then convert to csv with @csv:

$ curl -s ipinfo.io | jq '[.country, .city] | @csv'
"\"US\",\"Mountain View\""

The -r (raw) argument cleans up some of that escaping:

$ curl -s ipinfo.io | jq -r '[.country, .city] | @csv'
"US","Mountain View"

You can then use paste to combine the output with another file.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.