artemisia480
artemisia480

Reputation: 107

Parse JSON file in linux using jq

I have a json file, call it x.json satisfying this schema:

 }
      },
      "type": "persons"
    },
    "person's in a group": {
      "primary": {
        "attributes": {
          "firstname": "sara",
          "lastname": "jones",
          "age": "32",
          "weight": "130",

to get the list of first name, I have to write:

cat x.json | jq '.title[].type[].properties.firstname'

is there a shorter way to get the first name? Instead of having to write the whole line of objects? Also is there a way to list more than just the first name, for example first and last name? lastly, any idea how I can import this out into a CVS file or any other flat file system?

Upvotes: 0

Views: 7211

Answers (1)

tkruse
tkruse

Reputation: 10695

I edited your question in several ways. You provided a schema, not an example. also I think you mean the command jq, not jd.

Also I assume you have to parse a file containing a list of such persons, not just a single person.

With jq, you can run this

echo '
[{
  "firstName": "sin",
  "lastName": "minim sint labore"
},
{
  "firstName": "mun",
  "lastName": "minim sint labore"
}]' >> x.json

cat x.json | jq '.[].firstName'
"sin"
"mun"

jq has more options that you can find in their documentation, such as:

$ jq -c '.[] | [.firstName, .lastName]' x.json
["sin","minim sint labore"]
["mun","minim sint labore"]

For transforming such or other JSON output to CSV, look at the documentation, or use google or Stackoverflow.

Upvotes: 2

Related Questions