繁体   English   中英

如何将 json 数据添加到 node.js 中的 mysql 数据库

[英]How do i add json data to mysql database in node.js

我要从http://jsonplaceholder.typicode.com/users获取 json 数据

我想用来自 json 数据的 id、名称、用户名和 email 填充 mysql 数据库。 我正在使用一个名为“请求”的节点模块来读取在线 json api


const db = mysql.createConnection({
   host: 'localhost',
   user: 'root',
   password: '',
   database: 'nodemysql'
});
connect
db.connect((err) => {
   if (err) {
       throw err
   }
   console.log('MySql Connected...');

});
app.get('/populate', (req, res) => {
   request({
       url: "http://jsonplaceholder.typicode.com/users",
       json: true
   }, (err, res, body) => {
       res.send(body);
   });
})

这是 json api 中项目的两个样本

  {
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "Sincere@april.biz",
    "address": {
      "street": "Kulas Light",
      "suite": "Apt. 556",
      "city": "Gwenborough",
      "zipcode": "92998-3874",
      "geo": {
        "lat": "-37.3159",
        "lng": "81.1496"
      }
    },
    "phone": "1-770-736-8031 x56442",
    "website": "hildegard.org",
    "company": {
      "name": "Romaguera-Crona",
      "catchPhrase": "Multi-layered client-server neural-net",
      "bs": "harness real-time e-markets"
    }
  },
  {
    "id": 2,
    "name": "Ervin Howell",
    "username": "Antonette",
    "email": "Shanna@melissa.tv",
    "address": {
      "street": "Victor Plains",
      "suite": "Suite 879",
      "city": "Wisokyburgh",
      "zipcode": "90566-7771",
      "geo": {
        "lat": "-43.9509",
        "lng": "-34.4618"
      }
    },
    "phone": "010-692-6593 x09125",
    "website": "anastasia.net",
    "company": {
      "name": "Deckow-Crist",
      "catchPhrase": "Proactive didactic contingency",
      "bs": "synergize scalable supply-chains"
    }
  }

我只需要将 ID、名称、用户名和 email 添加到 mysql 数据库作为每个用户的列作为行

假如说

是的,它是版本 10.4.11 – Preshy Jones

意味着你有 MariaDB:

SELECT idx + 1, 
       JSON_VALUE(single_object, '$.id') id,
       JSON_VALUE(single_object, '$.name') name,
       JSON_VALUE(single_object, '$.username') username,
       JSON_VALUE(single_object, '$.email') email
FROM ( SELECT idx, JSON_EXTRACT(@json, CONCAT('$[', idx, ']')) single_object
       FROM ( SELECT 0 idx UNION SELECT 1 UNION SELECT 2) idxs ) objects
HAVING id;

小提琴

注意 - 单独的 JSON 对象作为 JSON 数组传输到查询中,而不是作为 JSON ZA8CFFDE6331BD4B666AC9。

'idxs' 子查询中的连续数字的数量必须从零开始,并且包含的数字至少与源数据中单个对象的数量一样多。 如果没有,剩余的行将丢失。 这个子查询可以很容易地用 numberlist 生成的递归 CTE 替换。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM