0

How can I (generically) transform the input file below to output file below, using jq:

Input file:

[{"a": 1, "b": 10},
 {"a": 2, "d": "fred", "e": 30}]

Output file:

INSERT INTO mytab (a,b) VALUES (1,10);
INSERT INTO mytab (a,d,e) VALUES (2,"fred",30);

1 Answer 1

2

Using a combination of string interpolation and two variants of string join operations, one using the @csv filter and other using join(",")

jq --raw-output '
  .[]| to_entries | map(.key) as $k | map(.value) as $v | 
    "INSERT INTO mytab (\($k | join(","))) VALUES (\($v | @csv ));"' 

jqplay demo

Sign up to request clarification or add additional context in comments.

8 Comments

Re "map(to_entries)[]", .[] | to_entries. Seems really weird to build an array only to flatten it immediately afterwards.
If its just a matter of style, I'd like to keep it this way.
Also, @csv? Will that do the right thing for strings that contain " or \ ?
@ikegami I'll leave it to the OP to decide, they want the values field to retain the original format, so can't use join for it
I don't understand. Whether @csv produces SQL literals or not is not something that needs to be decided.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.