1

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}
   ]
}
6
  • How was this data generated? Commented Mar 3, 2020 at 9:47
  • 1
    Note that is not ". Just read the input line by line with : as separator and output them in the formar {"something":"something"} then joni the lines with comma. How to read a file line by line How to join lines with delimeter Commented Mar 3, 2020 at 10:00
  • 1
    Your output is not valid JSON... Commented Mar 3, 2020 at 10:04
  • I have made changes in the question. Please check if that makes more sense Commented Mar 3, 2020 at 10:10
  • 1
    Your expected output is still not valid JSON. If you want something JSON-like but not, don't call it JSON. Commented Mar 3, 2020 at 10:24

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Can I append new pair (Key/value) to the existing array "test5": "test5" { "array": [ { "test": "test" }, { "test1": "test1" }, { "test4": "test4" }, { "test5”: "test5” } ] }
0

Assuming you want actual JSON output:

$ jq -nR '{array: (reduce inputs as $line ([]; . + [$line | split(":") | {(.[0]):.[1]}]))}' input.txt 
{
  "array": [
    {
      "test": "test"
    },
    {
      "test1": "test1"
    },
    {
      "test4": "test4"
    }
  ]
}

Comments

0

With the JSON-parser :

XPath:

$ xidel -s "input.txt" -e '
  {
    "array":x:lines($raw) ! {
      substring-before(.,":"):substring-after(.,":")
    }
  }
'

(x:lines($raw) is a shorthand for tokenize($raw,'\r\n?|\n') and turns $raw into a sequence where every new line is another item)

XQuery:

$ xidel -s "input.txt" -e '
  {
    "array":for $line in x:lines($raw)
      let $item:=tokenize($line,":")
      return {
      $item[1]:$item[2]
    }
  }
'

See also this xidelcgi demo.

Comments

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.