I have a file that contains this format:
Cus Id: 1234
Cus Name: 10:/John Parks
Cus Type: temporary
Cus client: tesla;toyota
Dept Id: 111
Cus Id: 1235
Cus Name: 10:/William Parks
Cus Type: temporary
Cus client:
Dept Id: 222
How can I convert this to JSON format? Any methods bash, jq, or python is fine.
[
{
"Cus Id": 1234,
"Cus Name": "10:/John Parks",
"Cus Type": "temporary",
"Cus client": "tesla;toyota",
"Dept Id": 111
},
{
"Cus Id": 1235,
"Cus Name": "10:/William Parks",
"Cus Type": "temporary",
"Cus client": "null",
"Dept Id": 222
}
]
3
Answers
outputs
A Python solution:
Prints:
You could
reduce
the stream of raw-text (flag-R
)inputs
(flag-n
) by iteratively building up the output array. Start with an array containing one empty object ([{}]
), thencapture
each line’s contents using regular expressions, and populate the currently last array item with it. If capturing fails structurally (testing the presence of a key), add another empty object.Demo
Going further:
$in.v
accordingly before the assignment. For example, to first test if values look like numbers and turn them into one, then test for empty strings and replace them with a special one ("null"
), or else use the given string, you could go with something like($in.v | tonumber? // (select(. == "") | "null") // .)
.map(select(. != {}))
.