1

Consider the table:

CREATE TABLE watermelon
(
    order_id integer,
    sort text,
    size integer,
    juiciness integer,
    sender text,
);

I have an incoming json looking like this:

{
    "order_id": 500,
    "items": [
        {
            "sort": "regularMidterranian",
            "size": 6,
            "juiciness": 85
        },
        {
            "sort": "yellowMexican",
            "size": 4,
            "juiciness": 90
        }
    ],
    "sender": "SantaClara"
}

Is there a way to neatly insert this json into the table in one query, thus creating 2 entries with all fields filled?

Or is it simpler to just modify the json beforehand, extracting JArray adding order_id & sender to all items and then using regular json_populate_record?

1 Answer 1

2

Use the JSON types in postgresql.

https://www.postgresql.org/docs/9.5/functions-json.html

You can substitute the literal JSON doc in the incoming CTE with a regular text bind parameter in your C#.

=# truncate table watermelon ;
TRUNCATE TABLE

=# with incoming as (
  select '{
    "order_id": 500,
    "items": [
        {
            "sort": "regularMidterranian",
            "size": 6,
            "juiciness": 85
        },
        {
            "sort": "yellowMexican",
            "size": 4,
            "juiciness": 90
        }
    ],
    "sender": "SantaClara"
  }'::jsonb as indata
), do_unnest as (
  select (indata->>'order_id')::int as order_id, 
         indata->>'sender' as sender,
         jsonb_array_elements(indata->'items') as item
    from incoming
)
insert into watermelon (order_id, sort, size, juiciness, sender)
select order_id, 
       item->>'sort' as sort, 
       (item->>'size')::int as size,
       (item->>'juiciness')::int as juiciness,
       sender
  from do_unnest;
INSERT 0 2

=# select * from watermelon;

 order_id |        sort         | size | juiciness |   sender   
----------+---------------------+------+-----------+------------
      500 | regularMidterranian |    6 |        85 | SantaClara
      500 | yellowMexican       |    4 |        90 | SantaClara
(2 rows)

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

Comments

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.