Problem
We have a list of IDs generated into a file F with this format:
|
|
We want to generate a JSON object from the IDs with this structure:
|
|
The way we do it
we use jq
- what is
jqjqis a lightweight and flexible command-line JSON processor. 轻量级的命令行JSON处理器,非常灵活
- what are the main features
jqis likesedforJSONdata- 你可以方便的使用它对结构化的数据进行
sliceandfilterandmapandtransform
- 你可以方便的使用它对结构化的数据进行
jqis written in portable C, and it has zero runtime dependencies.- 它没有运行时的依赖
- Tutorial
- Manual or you can run
man jq
How do we do it
the following is the code
|
|
Syntax of jq
-
–raw-input/-R: Don’t parse the input as JSON. Instead, each line of text is passed to the filter as a
string. If combined with –slurp, then the entire input is passed to the filter as a single long string. -
–null-input/-n: Don’t read any input at all! Instead, the filter is run once using null as the input. This is useful when using jq as a simple calculator or to construct JSON data from scratch.
-
inputandinputs, that read from the same sources (e.g., stdin, files named on the command-line) as jq itself.inputOutputs one new input.inputsOutputs all remaining inputs, one by one.
Explaination of the process
-
-Rmeans jq will treat the anything it gets as a string not a JSON. if you don’t use-Rand pass a string as input, it will throw error. -
-nmeans jq will not read any input. so it can work together withinputsto construct a JSON data.- if you do this
echo '1\n2\n3' | jq -R '[inputs]'you will only get["2","3"]. why? because without-njq will read a input, which is1, then theinputswill ouputs the remaining inputs, which are2\n3. - if you do this
echo '1\n2\n3' | jq -Rn '[inputs]', you will get["1","2","3"]. why? because with-njq will not read a input, so theinputswill outputs the remaining inputs, which are1\n2\n3.
- if you do this
-
select(length>0)for each input, it will filter out the empty input -
assemble_user(.)for each input, it will call the defassemble_user -
def assemble_user($user_id): {"user_id": $user_id}for each input like123, it will return a object like{"user_id": 123} -
<<<this symbol meansHere string<<<is known as here-string. Instead of typing in text, you give a pre-made string of text to a program. For example, with such program as bc we can do bc «< 54 to just get output for that specific case, no need to run bc interactively. Think of it as the equivalent of echo ‘54’ | bc.
check the difference between
<,<<,<<<here -
--argjsonmeans it has a JSON data as the argument. -
--argmeans it has a string data as the argument -
jq -n --argjson user_ids "$USER_IDS" --arg organisation_id "$ORGANISATION_ID"you can structure a JSON data easily.
The result
- So first step I get the array with objects.
- if you do this quickly
|
|
you will get:
|
|
- Second, I assemble them together as a object. you will get
|
|