Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
404 views
in Technique[技术] by (71.8m points)

Using JQ to convert plain text block to JSON

I have a plain text file in format like this:

foo: bar
color: blue
names: joe, john, mary, bob, sue

I need to output the contents of this file as a JSON format:

{
  "foo": "bar",
  "color": "blue",
  "names": ["joe", "john", "mary", "bob", "sue"]
}

I have tried using: jq -R -n '[inputs|split(":")|[{(.0):.[1] | add' testfile (let's say the name of the file is testfile) but I can only get this result:

{
  "foo": "bar",
  "color": "blue",
  "names": "joe, john, mary, bob, sue"
}

What do I need to do in order to get the desired output? I've tried piping split(",") after [1] but it makes every value pair into an array, which I don't want.

question from:https://stackoverflow.com/questions/65832707/using-jq-to-convert-plain-text-block-to-json

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Always split the value. If resulting array has multiple elements, then assign it; otherwise assign the original string.

reduce (inputs / ": ") as [$k, $v] (.;
  .[$k] = ($v / ", " | if has(1) then . else $v end)
)

Online demo

Or, check whether the value contains a separator first and then split, if that makes more sense.

          ($v | if index(", ") then split(", ") else . end)

Online demo

Note that you need to invoke JQ with -R and -n on the command line for this to work.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...