I’m trying to insert JSON data into my database from Jenkins pipeline, unfortunately I have problem with proper format.
My query looks like that:
def insertQuery = """
INSERT INTO public.metrics(pr, info) VALUES ('KP-1111', '{"key": "value"}');
"""
and later:
sh """
PGPASSWORD="${dbPassword}" psql -h ${dbHost} -p ${dbPort} -d ${dbName} -U ${dbUser} -c "${insertQuery}" -w
"""
Error I’m getting:
ERROR: invalid input syntax for type json
LINE 2: ... INTO public.metrics(pr, info) VALUES ('KP-1111', '{key: val...
^
DETAIL: Token "key" is invalid.
CONTEXT: JSON data, line 1: {key...
I tried to escape signs, move JSON into variable instead of hardcode in query. Is there any other option I can insert this data?
2
Answers
Your query’s JSON data is in the wrong format for PostgreSQL’s JSON type, which is why you’re seeing this error. JSON data must have keys that are double-quoted and enclosed in single quotes for PostgreSQL to accept it. Here’s how to change your query so that JSON data is successfully inserted:
Hope it works
You have quietly mismatched quotes. The
query
string haskey
andvalue
surrounded in double quotes, then thesh
again surrounds the entirequery
in double quotes, so your-c "${insertQuery}"
ends up evaluated to:which terminates the string at the double quote before
key
, concatenates it withkey
, reopens quoted string and continues up untilvalue
and does the same, cutting it up like this:So you end up losing those double quotes entirely. Which is why you can see the error message without them around
key
andvalue
:You can escape the quotes with
to avoid them terminating the string in your
sh
: