Using Python to insert JSON into PostgreSQL

I have the following table:

create table json_table (
    p_id int primary key,
    first_name varchar(20),
    last_name varchar(20),
    p_attribute json,
    quote_content text
)

Now I basically want to load a json object with the help of a python script and let the python script insert the json into the table. I have achieved inserting a JSON via psql, but its not really inserting a JSON-File, it’s more of inserting a string equivalent to a JSON file and PostgreSQL just treats it as json.

What I’ve done with psql to achieve inserting JSON-File:

Reading the file and loading the contents into a variable

set content type C:PATHdata.json

Inserting the JSON using json_populate_recordset() and predefined variable ‘content’:

insert into json_table select * from json_populate_recordset(NULL:: json_table, :'content');

This works well but I want my python script to do the same.
In the following Code, the connection is already established:

connection = psycopg2.connect(connection_string)
cursor = connection.cursor()
cursor.execute("set search_path to public")


with open('data.json') as file:
        data = json.load(file)

query_sql = """
insert into json_table select * from
json_populate_recordset(NULL::json_table, '{}');
""".format(data)

cursor.execute(query_sql)

I get the following error:

Traceback (most recent call last):
  File "C:/PATH", line 24, in <module>
    main()
  File "C:/PATH", line 20, in main
    cursor.execute(query_sql)
psycopg2.errors.SyntaxError: syntax error at or near "p_id"
LINE 3:     json_populate_recordset(NULL::json_table, '({'p_id': 1, ...

If I paste the JSON content in pgAdmin4 and use the string inside json_populate_recordset() it works. I assume im handling the JSON file wrong…

My data.json looks like this:

(
    {
        "p_id": 1,
        "first_name": "Jane",
        "last_name": "Doe",
        "p_attribute": {
            "age": "37",
            "hair_color": "blue",
            "profession": "example",
            "favourite_quote": "I am the classic example"
        },
        "quote_content": "'am':2 'classic':4 'example':5 'i':1 'the':3"
    },
    {
        "p_id": 2,
        "first_name": "Gordon",
        "last_name": "Ramsay",
        "p_attribute": {
            "age": "53",
            "hair_color": "blonde",
            "profession": "chef",
            "favourite_quote": "Where is the lamb sauce?!"
        },
        "quote_content": "'is':2 'lamb':4 'sauce':5 'the':3 'where':1"
    }
)

nodelist – How do I divide bodycontent in two halves and insert html in the middle using Pure Javascript

I’ve done it with jQuery, but need to do it with PURE JS.

jQuery example:

$(document).ready(function() {
  var bodyContent = Math.floor($('#content').children().length);
  var bodyContentDividedInTwo = Math.floor(bodyContent / 2);

   $('#content').children(':eq('+bodyContentDividedInTwodedInHalf+')').after(`widget goes here`);
});

This is where I’m stuck with my PURE JS example:

 var fullBodyContent = document.querySelector('#contentBody');
        var bodyContentSplitInHalf = fullBodyContent.childElementCount / 2;

       bodyContentSplitInHalf.insertAdjacentHTML('afterbegin', '<h1>Yeeeeeeesssss!</h1>');

Then I get the obvious error of it not being a function. Because its a nodelist.

Please help, I know this is an easy one. But for some reason I always struggle to figure this out.

algorithms – Problem to Insert at n-th position in a singly circular linked list of integers

Here’s my code to insert a node at n-th position in a singly circular linked list. When tail is NULL , I’m trying to just return but that gives me a run time error. For this particular code, I am getting 8 printed while tail is NULL and not when pos==1 which should be the case. And for this wrong insertion pattern, I’m getting a list printed in reverse order when display() is called.

void insert(int data, int pos)
{
struct node *temp1 = (struct node *)malloc(sizeof(struct node));
temp1->data = data;
struct node *temp2;
if(tail == NULL)
{
temp1->link=temp1;
tail=temp1;
}
if( pos == 1)
{

    temp1->link=tail->link;
    tail->link=temp1;
}
else
{
    temp2 = tail->link;
    for(int  i=1; i<pos-1; i++)
    {
        temp2 = temp2->link;
    }

    temp1->link = temp2->link;
    temp2->link = temp1;
}

}

main()
{
tail=NULL;
insert(8,1);
display();
insert(3,2);
display();
insert(7,3);
display();
insert(9,4);
display();
It prints 9->7->3->8 and not 8->3->7->9.

INSERT DB

Please I need a little help, I am only learning SQL.

I need t o INSERT into the DB, a new hotel called ‘Beach Resort’ at location ‘Mexico’.
This is what i have: (Note that the value ‘8’ is because ‘hotelNo’ in all tables is NOT AUTO_INCREMENT. but it is a int(11) NOT NULL

INSERT INTO hotel VALUES (‘8′,’Beach Resort’,’Mexico’)

‘hotelNo’ is the PRIMARY KEY in all tables. If I manually update hotelNo with above script in Hotel table, do i need to update it manually in all tables?
SEMrush

This is MySQL DB in WorkBench

Hotel (hotelNo, hotelName, city)
Room (roomNo, hotelNo, type, price)
Booking (hotelNo,guestNo, dateFrom, dateTo, roomNo)
Guest (guestNo, guestName, guestAddress)

-Hotel contains hotel details and hotelNo is the primary key
-Room contains room details for each hotel and (roomNo, hotelNo) forms the primary key
-Booking contains details of bookings and (hotelNo,guestNo,dateFrom) forms the primary key
-Guest contains guest details and guestNo is the primary key

Any help appreciated

 

c++ – Insert element into struct vector

I want to initialize a struct using a function and also insert into it as seen below. This is what I have written so far. I do not know if this makes any sense. I want to initialize the array dynamically and adjust the current_size and max-size. No external library is to be used

struct vector{
    int current_size;
    int max_size;
    int *array;

};


void initialize(vector &vec, int size){
    vec.current_size=size;
    vec.array(size);
    vec.max_size=size;

}
void insert( vector &vec, int element){
        vec.array(vec.current_size)=element;
        vec.current_size++;


}

nosql – insert many documents into the collection, but only unique items based on a specific field. MongoDB

I can't seem to find an answer anywhere. I need the following:

Given an array of objects with the structure:

{
   link: 'some-link',
   rating: 25,
   otherFields: '..',
   ...
}

I want to insert them into my collection. So I would just do insertMany... But I only want to insert those elements of the array that are unique, meaning that I do not want to insert objects with the field "link" being something that is already in my collection.

Meaning if my collection has the following documents:

{
  _id: 'aldnsajsndasd',
  link: 'bob',
  rating: 34,
}
{
   _id: 'annn',
   link: 'ann',
   rating: 45
}

And I do the "Update / Insert" with the following array:

[{
  link: 'joe', 
  rating: 10
},{
  link: 'ann',
  rating: 45
}, {
  link: 'bob',
  rating: 34
}, {
  link: 'frank',
  rating: 100
}]

Documents only:

{
  link: 'frank',
  rating: 100
}
{ 
  link: 'joe',
  rating: 10
}

Would be added to my collection

How do I insert data into Paypal SDK classes using the Laravel model?

I have to integrate PayPal into my Laravel application. I have classified my model class in one of the Paypal SDK classes, which is located in the app / library. Now is the thing before the transaction process is complete. An error occurred while inserting my server-side scripts in the PayPalCaptureOrder class. which is given below:

Object of class PayPalHttpHttpResponse could not be converted to string {"exception":"(object) 
(ErrorException(code: 0): Object of class PayPalHttp\HttpResponse could not be converted to string 
at 
C:\Apache24\htdocs\Abtach\PayPalIntegration\vendor\
laravel\framework\src\Illuminate\Support\Str.php:419

What I really don't understand if I store my data in a database while making an API call, why is the above error displayed? I mean, API calling and inserting data into the database are two different things.

python 3.x – HOW TO INSERT DICTIONARY KEY (CPF) IN ANOTHER DICTIONARY WITH CUSTOMER DATA (NAME, TELEPHONE, etc.).

Write a program that you can use to manage a company's customer database. Customers are stored in a dictionary in which each customer's key is their CPF, and the value is another dictionary with the customer data (name, address, phone, email, preferred).