Timmo
Timmo

Reputation: 2334

Bash Script - irsend LIST Output to JSON

I have this command:

irsend LIST lgtv ""

which outputs like this:

irsend: 00000000000010ef KEY_POWER
irsend: 0000000000008877 KEY_1
irsend: 00000000000048b7 KEY_2
irsend: 000000000000c837 KEY_3
irsend: 00000000000028d7 KEY_4
irsend: 000000000000a857 KEY_5
irsend: 0000000000006897 KEY_6
irsend: 000000000000e817 KEY_7
irsend: 00000000000018e7 KEY_8
irsend: 0000000000009867 KEY_9
irsend: 00000000000008f7 KEY_0

How do I grab each line and get the codes and key name and output them into JSON format?

EG:

[
    {"code": "00000000000010ef", "key": "KEY_POWER" },
    {"code": "0000000000008877", "key": "KEY_1" },
    {"code": "00000000000048b7", "key": "KEY_2" }
]

Upvotes: 1

Views: 166

Answers (2)

peak
peak

Reputation: 116720

The key here is the -R command-line option, which allows lines to be read one-at-a-time. With your input, the following invocation produces the results shown (truncated):

$ jq -c -R 'split(" ") | {code: .[1], key: .[2]}' input.txt
{"code":"00000000000010ef","key":"KEY_POWER"}
{"code":"0000000000008877","key":"KEY_1"}
{"code":"00000000000048b7","key":"KEY_2"}

You might want to consider tokenizing the input string, e.g. if your jq has splits/1:

[splits(" +")] | {code: .[1], key: .[2]}

Notice that splits/1 produces a stream, whereas split/1 produces an array.

If you want the result as a single array, then you could pipe the above into jq -s ..

Upvotes: 3

kabanus
kabanus

Reputation: 25895

Using AWK for your example:

irsend LIST lgtv "" | awk 'BEGIN{print "["}{{printf("{'"'"'code'"'"' : '"'"'%s'"'"', '"'"'key'"'"', '"'"'%s'"'"'}\n",$2,$3)}END{print "]"}'

The crazy '"'"' construct makes sure a ' is actually output. Using double quotes is easier (and JSONier):

irsend LIST lgtv "" | awk 'BEGIN{print "["}{{printf("{\"code\" : \"%s\", \"key\", \"%s\"}\n",$2,$3)}END{print "]"}'

Upvotes: 1

Related Questions