G Doe
G Doe

Reputation: 41

Add JSON Pair to JSON File Based on CSV

I have a csv, ids.csv, in this format:

id,name,slug
12345,Case A,case-a-12345
12824,Case B,case-b-12824

and a bunch of json files in a folder that match a name in the csv, like Case A.json, in this format:

{
  "type": "mass"
  "features": [
  {
      "type": "sub",
      "properties": {
        "key1": "value1",
        "key2": "value2"
      }
    }
  ]
}

and I want to match the name in the csv to the name of the json file and add in the id, name, and slug to the properties so I get this:

{
  "type": "mass"
  "features": [
  {
      "type": "sub",
      "properties": {
        "key1": "value1",
        "key2": "value2",
        "id": "12345",
        "name": "Case A",
        "slug": "case-a-12345

      }
    }
  ]
}

So far I only know how to add values using jq like such:

jq '.features[0].properties | .key3="value3"'

How do I go about extracting my value from a csv, matching it with the right json file, and applying it to all my json files?

Upvotes: 2

Views: 77

Answers (1)

chepner
chepner

Reputation: 531918

You can use the += operator, once you have extracted the correct fields from the CSV file. I don't recommend using bash for that, but as long as you don't have any quoted commas in field values, you can get away with a simple while loop.

{
    read   # Skip the header
    while IFS=, read -r id name slug; do
        jq --args id "$id" \
           --args name "$name" \
           --args slug "$slug" \
           'features[0].properties += {id: $id, name: $name, slug: $slug}' "$name.json" > tmp && mv tmp "$name.json"
    done
} < ids.csv

Upvotes: 3

Related Questions