gpt4 book ai didi

javascript - 将 JSON 数据编辑为 Firebase 格式

转载 作者:行者123 更新时间:2023-11-30 20:50:06 26 4
gpt4 key购买 nike

我有一种格式的 json 数据,需要编辑为 Firebase 支持的格式。我创建了一个具有尝试编辑数据格式功能的 javascript 应用程序,但似乎不起作用。数据量很大,但下面是一个示例。

app.js 应用程序

var fs = require('fs');

//read data from file
var readData = fs.readFileSync('readMe.json','utf8');
var sample = JSON.parse(readData);

var newData =addFirebaseKey(sample);


// output datda to output.json
fs.writeFileSync('output.json',JSON.stringify(newData),'utf8');

function addFirebaseKey(contacts){
var fireContacts="";
for(var i=0;i<contacts.length;i++){
var tempObj=contacts[i];

//tel number is also the firebase key
var fireKey =tempObj.tel;

fireContacts=fireContacts+fireKey+tempObj;
}
return fireContacts;
}

readMe.json 文件

[
{
"contactName": "Office of the President",
"description": "office of president",
"fax": "-",
"location": "Lusaka",
"postalAddress": "-",
"tel": "123456",
"country": "Zambia"
},
{
"contactName": "State House",
"description": "State president, Ministry of",
"fax": "-",
"location": "Lusaka",
"postalAddress": "-",
"tel": "444900",
"country": "Zambia"
},
{
"contactName": "National Strategy Office",
"description": "national strategy",
"fax": "-",
"location": "Gaborone",
"postalAddress": "-",
"tel": "222222",
"country": "Zambia"
}
]

输出.json文件

"123456[object Object]444900[object Object]222222[object Object]"

这是 Firebase 所需的格式

{
"contactDetail" : {
"Zambia" : {
"123456" : {
"contactName" : "Shocks & Exhaust Fitment Centre",
"description" : "motor vehicle exhaust systems",
"fax" : "-",
"location" : "Lusaka",
"postalAddress" : "NA",
"tel" : "123456"
},
"888555" : {
"contactName" : "K Media",
"description" : "internet marketing",
"fax" : "-",
"location" : "Lusaka",
"postalAddress" : "P O Box 26249, Gaborone",
"tel" : "888555"
},
"555544" : {
"contactName" : "Shocks & Exhaust Fitment Centre",
"description" : "secretarial services",
"fax" : "-",
"location" : "Lusaka",
"postalAddress" : "NA",
"tel" : "555544"
}
}
}
}

最佳答案

转换数据格式:

let input = [
{
"contactName": "Office of the President",
"description": "office of president",
"fax": "-",
"location": "Lusaka",
"postalAddress": "-",
"tel": "123456",
"country": "Zambia"
},
{
"contactName": "State House",
"description": "State president, Ministry of",
"fax": "-",
"location": "Lusaka",
"postalAddress": "-",
"tel": "444900",
"country": "Zambia"
},
{
"contactName": "National Strategy Office",
"description": "national strategy",
"fax": "-",
"location": "Gaborone",
"postalAddress": "-",
"tel": "222222",
"country": "Zambia"
}
];

let output = {};
input.forEach((row) => {
if (!output[row.country]) output[row.country] = {};
output[row.country][row.tel] = row;
})
console.log(output);

之后,您需要将其写入 Firebase 或文件。

关于javascript - 将 JSON 数据编辑为 Firebase 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48270414/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com