1

I have incoming json structure like

{
    "type":1,
    "location":[
        {"lattitude":"0", "longitude":"0"},
        {"lattitude":"0", "longitude":"0"},
        {"lattitude":"0", "longitude":"0"}]
}

I need to insert this into a database like

|------|-----------|-----------|
| type | lattitude | longitude |
|------|-----------|-----------|
| 1    | 0         | 0         |
|------|-----------|-----------|
| 1    | 0         | 0         |
|------|-----------|-----------|
| 1    | 0         | 0         |
|------|-----------|-----------|

how do I parse the json and build an sql query?

2
  • Is your json structure constant or varying ? Postgres has json related functions which can work on json directly within a Postgres function call and constructing a query won't be needed. Commented Jun 27, 2019 at 4:46
  • @KaushikNayak it's always in this form Commented Jun 27, 2019 at 4:53

2 Answers 2

2

If you want to use Postgres solution, you may do

--INSERT INTO yourtab( type,lattitude,longitude)

select jsoncol->>'type' , j->>'lattitude'
             j->>'longitude'
 from
 ( values (:yourjsonstr :: jsonb ) ) as t(jsoncol) cross join 
          lateral jsonb_array_elements(jsoncol->'location')
                                   as j;

DEMO

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

Comments

1

You can use json-sql

Example:

var sql = jsonSql.build({
    type: 'insert',
    table: 'users',
    values: {
        name: 'John',
        lastname: 'Snow',
        age: 24,
        gender: 'male'
    }
});

sql.query
// insert into users (name, lastname, age, gender) values ($p1, $p2, 24, $p3);

sql.values
// { p1: 'John', p2: 'Snow', p3: 'male' }

See the documentation: https://www.npmjs.com/package/json-sql

2 Comments

is this faster than inserting multirow values?
@niga I don't think there will be a large difference

Your Answer

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