我有一个函数,可以连接到 api 并提取许多不同项目的article
、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()
});
}
最佳答案
遵循 official documentation告诉 writeFileSync 可以这样使用:
const fs = require("fs");
const json = { /* Big object of whatever */ };
const path = "path/file.json";
fs.writeFileSync(path, JSON.stringify(json));
我在您的代码中看不到任何fs.writeFileSync
,但我猜这就是您想要做的。
关于javascript - 保存 json 文件时遇到的困难,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59536233/