I have a text file with contents:
//input.txt
1) What is the first month of the year?
a) March
b) February
c) January
d) December
Answer: c) January
2) What is the last month of the year?
a) July
b) December
c) August
d) May
Answer: b) December
I would like to write a shell script that loops through this file input.txt (which has many more contents with the same format) and produce an output similar to the below JSON
[
{
"question": "What is the first month of the year?",
"a": "March",
"b": "February",
"c": "January",
"d": "December",
"answer": "January",
},
{
"question": "What is the last month of the year?",
"a": "July",
"b": "December",
"c": "August",
"d": "May",
"answer": "December",
},
[
I started by trying to write a bash script, to loop through the file and put each line separated by an empty line into curly brackets, and each item in the curly brackets into quotation marks, and separated by a comma, but it isn’t working
#!/bin/bash
output=""
while read line; do
if [ -z "$line" ]; then
output+="}n"
else
output+=""${line}","
if [ $(echo "$output" | tail -n 1) == "" ]; then
output+="{"
fi
fi
done < input.txt
output+="}"
echo "$output" > output.txt
3
Answers
Here is one way using jq:
Online demo
You will pull all your hair out trying to generate proper JSON with Bash.
First, your example JSON output is not proper JSON. The trailing
,
are not supported in arrays and mappings. So you example needs to be:(Note no
,
after each"answer"
or after the final}
. You check for valid JSON with a tool or jsonlint)To generate that from your input, there are many JSON generator tools. The easiest for ME is Ruby:
Prints:
Two different approaches (with the same result) with the JSON-parser xidel: