I got a json variable in which i got all my data. I'd like to take a specific key and its value to insert it in a specific column of my table.
Here is an example:
{
'Code bati': 'Pas',
Etage: '0',
Zone: 'FST',
'Pièce': '000',
'Priorité': 5,
'Désignation': 'Salle de cours',
'Type d’installation': '',
'Date de mise en service': '',
"Date d'installation": '',
Maintenance: '',
'Entreprise ayant le contrat de maintenan': '',
'Date de visite': 44525,
Marque: 'Epson',
'Modèle': 'EB-1980WU',
'N° série': 'V5YF630231L',
'Heure Lampe': 1796,
Position: 'centré',
HDMI: 'oui',
VGA: 'oui',
Video: 'non',
Automate: 'MLC ???',
Liaison: 'RS232',
'Type écran': 'manuel',
'Cage sécurité': 'oui',
'Statut HDMI': 'à tester',
'Statut VGA': 'à tester'
},
Here is my array, i'd like to take for example the key 'Zone' and its attribute 'FST' to insert them in a specific table of my postgres database. Do you have a solution for me ?
CodePudding user response:
It is a bit unclear to me if you have already installed PG lib for node. I have used this one in the past (when I needed something simple and fast): https://www.npmjs.com/package/pg.
Anyways, let's say you have this JSON in a variable, then you would like to parse that into an object, and then you can pick and choose whatever you want, and insert into the db.
Btw, your JSON is not formatted correctly, it is already formatted as an object... in the yourJSON var below I have formatted it correctly for you (by taking what you had, and wrapping it with JSON.stringify(whatYouHad))
const yourJSON = '{"Code bati":"Pas","Etage":"0","Zone":"FST","Pièce":"000","Priorité":5,"Désignation":"Salle de cours","Type d’installation":"","Date de mise en service":"","Date d'installation":"","Maintenance":"","Entreprise ayant le contrat de maintenan":"","Date de visite":44525,"Marque":"Epson","Modèle":"EB-1980WU","N° série":"V5YF630231L","Heure Lampe":1796,"Position":"centré","HDMI":"oui","VGA":"oui","Video":"non","Automate":"MLC ???","Liaison":"RS232","Type écran":"manuel","Cage sécurité":"oui","Statut HDMI":"à tester","Statut VGA":"à tester"}';
const parsedJSON = JSON.parse(yourJSON);
const query = 'INSERT INTO your_table (zone) VALUES ($1);
const bindings = [parsedJSON.Zone];
const insertResult = await dbClient.query(query, bindings);
console.log(insertResult);
You would need to clarify some more otherwise...