[英]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.