【问题标题】:How do I insert a specific key: value of Json into a postgres table using Node.js如何使用 Node.js 将特定键:Json 的值插入到 postgres 表中
【发布时间】:2022-01-19 10:28:02
【问题描述】:

我有一个 json 变量,我在其中获取了所有数据。我想将一个特定的键和它的值插入到我表的特定列中。

这是一个例子:

{
    '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'
  },

这是我的数组,我想以键“Zone”及其属性“FST”为例,将它们插入到我的 postgres 数据库的特定表中。 你有解决办法吗?

【问题讨论】:

  • sql语句:UPDATE your_target_table SET your_taget_column = your_json_data->>'Zone' WHERE your_condition_to select_the_row_to_update

标签: node.js arrays json postgresql insert


【解决方案1】:

我有点不清楚你是否已经为 node.js 安装了 PG lib。我过去曾使用过这个(当我需要一些简单而快速的东西时): https://www.npmjs.com/package/pg.

无论如何,假设您将这个 JSON 保存在一个变量中,然后您想将其解析为一个对象,然后您可以选择任何您想要的内容,然后插入到数据库中。

顺便说一句,你的 JSON 格式不正确,它已经被格式化为一个对象......在下面的 yourJSON var 中,我已经为你正确格式化了它(通过获取你所拥有的,并用 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);

否则你需要澄清一些......

【讨论】:

  • 好吧,我试过你的代码,它工作得很好,所以谢谢。我的解释可能不是很清楚,对此我深表歉意。我尝试创建一个脚本,但我并不总是理解我在做什么......这很难说清楚。无论如何,谢谢你的帮助
  • 一切都好。乐于助人:)
猜你喜欢
  • 1970-01-01
  • 2014-08-17
  • 1970-01-01
  • 1970-01-01
  • 2021-08-03
  • 2015-12-25
  • 2021-07-19
  • 2014-01-15
  • 1970-01-01
相关资源
最近更新 更多