arraysjsonbashshell

convert data of text file into JSON array in bash


I want output in the below JSON array format with command on linux/bash platform . Can anybody help

data in text file

test:test
test1:test1
test4:test4

Expecting output:

{array : 
   [
     {test:test},
     {test1:test1}, 
     {test4:test4}
   ]
}

Solution

  • Using jq command line JSON parser:

    <file jq -Rs '{array:split("\n")|map(split(":")|{(.[0]):.[1]}?)}'
    {
      "array": [
        {
          "test": "test"
        },
        {
          "test1": "test1"
        },
        {
          "test4": "test4"
        }
      ]
    }
    

    The options Rs let jq read the whole file as one string.

    The script splits this string into pieces in order to have the expected format.