9

I have test.json file with different lengths of rows. Some fictitious example:

{ "a" : 123, "b": "sd", "c": 45, "d": 1, "e": "" }
{ "a": 5, "b": "bfgg", "c": "x4c", "d": 31, "e": "" }

I want to just keep just b for every line:

{ "b": "sd"}
{ "b": "bfgg"}
12

With a proper jq tool:

jq -c '{"b": .b}' test.json

The output:

{"b":"sd"}
{"b":"bfgg"}
7

With Miller

$ mlr --json cut -f b test.json
{ "b": "sd" }
{ "b": "bfgg" }
3

Using the json json parser:

json -f test.json -gac 'return console.log("{ \"b\": \"" + this.b + "\" }")'

In this case jq seems like a better tool for this but I still think json is a really great tool for parsing json data.

2

You can try this with cut and sed:

cut -d',' -f2 file | sed -e 's/^/{/' -e 's/$/ }/'

Output:

{ "b": "sd" }
{ "b": "bfgg" }
  • Is this location dependant? I can't decypher why this works specifically for key b. – Mast Dec 13 '19 at 10:07
  • 1
    This works only because the example input always has "b" in the 2nd field. So it might be useful if you're on some system where you can't/don't want to install one of the fancier tools, but ONLY IF you can be absolutely sure the json formatting will never change. – Guntram Blohm supports Monica Dec 13 '19 at 10:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.