[英]Difficulties in saving a json file
我有一個連接到 api 並為許多不同項目提取particle
、 name
和community_price
的函數。 它運行良好,但現在我希望它將數據保存在 json 文件中。 它應該是這樣的:
[
{
"particle": "xxx",
"name": "xxx",
"community_price": "xxx"
},
{
"particle": "xxx",
"name": "xxx",
"community_price": "xxx"
},
{
"particle": "xxx",
"name": "xxx",
"community_price": "xxx"
}
]
我花了很多時間玩fs.writeFileSync
但不幸的是,由於我對 js 的了解不足,我的嘗試都沒有奏效。 歡迎任何幫助,將選擇最佳答案。 提前致謝!
這是函數:
function get_community_price(){
let url = 'https://example.com/api/IGetPrices/v4?key=' + backpackkey;
var massive;
let quality = '5';
request({url:url, json:true}, function(err, res, body){
if (err) console.log(err);
massive = body.response.items;
console.log('recieved comminty prices')
for(let i = 0; i < data.length; i += 1){
let get_json = other.urltojson(data[i].ApiLink);
let particle = get_json.particle
let name = data[i].BuyLink;
name = name.replace(/(\/Tradable).*/, '');
name = name.replace(/.*(\/)/, '');
name = name.replace(/\%20/g, ' ');
name = name.replace(/\%27/g, '\'')
let community_price = massive[name].prices[quality].Tradable.Craftable[particle].value;
data[i].BuyPrice = community_price;
}
CreateOrders()
});
}
這是我認為應該是的,但仍然不起作用。
function get_community_price(){
let url = 'https://example.com/api/IGetPrices/v4?key=' + backpackkey;
var massive;
let quality = '5';
request({url:url, json:true}, function(err, res, body){
if (err) console.log(err);
massive = body.response.items;
console.log('recieved comminty prices')
for(let i = 0; i < data.length; i += 1){
let get_json = other.urltojson(data[i].ApiLink);
let particle = get_json.particle
let name = data[i].BuyLink;
name = name.replace(/(\/Tradable).*/, '');
name = name.replace(/.*(\/)/, '');
name = name.replace(/\%20/g, ' ');
name = name.replace(/\%27/g, '\'')
let community_price = massive[name].prices[quality].Tradable.Craftable[particle].value;
data[i].BuyPrice = community_price;
var priceLog = [];
priceLog.push({particle, name, community_price});
}
fs.writeFileSync('./app/comPrice.json', JSON.stringify(priceLog, null, 4));
console.log('Fresh community price saved.');
CreateOrders()
});
}
按照官方文檔說明可以這樣使用 writeFileSync:
const fs = require("fs");
const json = { /* Big object of whatever */ };
const path = "path/file.json";
fs.writeFileSync(path, JSON.stringify(json));
我在您的代碼fs.writeFileSync
不到任何fs.writeFileSync
,但我想這就是您想要做的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.