1

I have a string which is formated as a long string (no newlines) like so:

<NAME1>ID1>CODE1a>CODE1b>><NAME2>ID2>CODE2a>CODE2b>><NAME3>ID3>CODE3a>CODE3b>>

The idea is convert this string to JSON:

{
  "ID1": [
    "NAME1",
    "CODE1a",
    "CODE1b"
  ],
  "ID2": [
    "NAME2",
    "CODE2a",
    "CODE2b"
  ],
  "ID3": [
    "NAME3",
    "CODE3a",
    "CODE3b"
  ]
}

The question is I need that in one comand (something like cat testfile.txt | sed "..." | tr "...")

I've tried to use sed, tr, jq, but no success, and I'm completely stuck. Thanks in advance

0

1 Answer 1

1

The whole thing can be done using just jq, e.g.:

jq -R '
  sub("^<";"")
  | split(">><")
  | map(split(">"))
  | map( { (.[1]) : (.[0:1] + (.[2:] | map(select(.!="")))) } )
  | add
'
Sign up to request clarification or add additional context in comments.

4 Comments

It is getting error: tio.run/…
Sorry - there was a typo. Fixed.
Perfect! I'll accept this one as the answer, because it's only using jq, although the other one does the job also! Just one question, how is used the split function and why did you have (wrongly) the two args?
split(STRING) splits the input string at STRING, producing an array. (See the manual regarding the difference between split and splits.) As for the typo - the original version I developed had a call to gsub(_;_) and I incorrectly edited it.

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.