Split a string field into an array in jq?

26,015

You're making it a lot more complicated than it is. Just use map() and |=:

jq 'map(.tags |= split(" "))' file.json

Edit:

If you want to handle entries without tags:

jq 'map(try(.tags |= split(" ")))' file.json

Alternatively, if you want to keep unchanged all entries without tags:

jq 'map(try(.tags |= split(" ")) // .)' file.json

Result:

[
  {
    "tags": [
      "tagA",
      "tag-B",
      "tagC"
    ],
    "title": "Some Title"
  },
  {
    "tags": [
      "tagA",
      "tagC"
    ],
    "title": "Some Title 2"
  }
]
Share:
26,015

Related videos on Youtube

leeand00
Author by

leeand00

Projects jobdb - Creator of Open Source Job Search Document Creator/Tracker http://i9.photobucket.com/albums/a58/Maskkkk/c64nMe.jpg Received my first computer (see above) at the age of 3, wrote my first program at the age of 7. Been hooked on programming ever since.

Updated on September 18, 2022

Comments

  • leeand00
    leeand00 about 1 month

    I have a JSON array returned from curl that looks like this:

    [
     {
       "title": "Some Title",
       "tags":"tagA tag-B tagC"
     },
     {
       "title": "Some Title 2",
       "tags":"tagA tagC"
     },
     ...
    ]
    

    I'd like to convert it to...

    [
     {
       "title": "Some Title",
       "tags":["tagA",
               "tag-B",
               "tagC"]
     },
     {
       "title": "Some Title 2",
       "tags":["tagA", 
               "tagC"]
     },
     ...
    ]
    

    So far I have:

    (map(select(.tags!=null)) | map(.tags | split(" "))) as $tags | $tags

    and that appears to give me something like:

         [
          [
           "tagA",
           "tag-B",
           "tagC"
          ],
          [
           "tagA", 
           "tagC"
          ]
         ]
    

    But I don't seem to be able to weave that back into an output that would give me .tags as an array in the original objects with the original values...

  • leeand00
    leeand00 over 5 years
    Okay I still needed to filter out the nulls first with 'map(select.tags!=null))' with my dataset, but you are correct that does work.
  • Satō Katsura
    Satō Katsura over 5 years
    @leeand00 Edited.
  • Admin
    Admin about 4 years
    OP specifically asks for jq.
  • Admin
    Admin over 2 years
    While this answer is not per OP's original request, and I really would avoid using sed for this job if at all possible, I don't think this deserves a down-vote. For those in a tight spot, POSIX options may be their only option and I see this answer as having value for that reason alone. That said, your sed skills are scary good.
  • Admin
    Admin over 1 year
    I agree. Also, jq isn't available everywhere, centos for example isn't providing it and you have to install epel to get it. In a CI deployment knowing how to do stuff with base tools without having to install stuff is a must have skill.