0

I want to process JSON data using jq. Here is an excerpt from the data:

{
  "lat": "49.3877286",
  "lon": "6.704062",
  "tag": [
    {
      "k": "name",
      "v": "Beckingen"
    },
    {
      "k": "is_in",
      "v": "Merzig-Wadern,Saarland,Bundesrepublik Deutschland,Europe"
    },
    {
      "k": "place",
      "v": "town"
    },
  ]
}
{
  "lat": "49.287307",
  "lon": "6.8827786",
  "tag": [
    {
      "k": "name",
      "v": "Püttlingen"
    },
    {
      "k": "place",
      "v": "town"
    },
    {
      "k": "population",
      "v": "18748"
    }
  ]
}

I need to extract the lat, lon, and name fields, like this:

{
  "lat": "49.3877286",
  "lon": "6.704062",
  "name": "Beckingen"
},
{
  "lat": "49.287307",
  "lon": "6.8827786",
  "name": "Püttlingen"
}

I'm almost there, but I can't figure out how to select a field from an array using select(). Can anyone point me in the right direction?

Many thanks,

Enno

2 Answers 2

3

Depending on your precise requirements, you could use map(select(...)) or .[] | select(...), along the lines of, for example:

.tag[] | select(.k == "name") | .v

You might want to make this more robust, for example by taking into account the possibility that there might not be exactly one "name":

first(.tag[] | select(.k == "name") | .v // null)
Sign up to request clarification or add additional context in comments.

Comments

0

Ok, I got it:

{lat: .lat, lon: .lon, tag: .tag[]}
| select(.tag.k=="name") 
| {lat: .lat, lon: .lon, name: .tag.v}

The trick was to use .tag[] which multiplies each entry with the number of array elements in .tag, then to select the relevant entries and then to construct the output JSON. Thanks for the hint, @peak!

2 Comments

You could simplify that to {lat, long, name: (.tag[] | select(.k == "name") | .v)}
Cool, thanks! For the sake of completion: in this particular case it was lon, not long.

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.