将 JSON 转换为 Javascript 数组对象 - node.js
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30793965/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert JSON to Javascript Array Object - node.js
提问by MayNotBe
I don't know any Javascript. I have a .json file that looks like this:
我不知道任何 Javascript。我有一个 .json 文件,看起来像这样:
{ "results": [
{
"challenger": {
"__type": "Pointer",
"className": "Player",
"objectId": "STWAxAHKay"
},
"challengerScore": 18,
"createdAt": "2014-12-05T21:43:01.099Z",
"defender": {
"__type": "Pointer",
"className": "Player",
"objectId": "UGAmRVd7Tr"
},
"defenderScore": 21,
"objectId": "pmiACGwe45",
"updatedAt": "2014-12-05T21:43:01.099Z"
},
{
"challenger": {
"__type": "Pointer",
"className": "Player",
"objectId": "STWAxAHKay"
},
"challengerScore": 23,
"createdAt": "2014-12-05T21:43:01.969Z",
"defender": {
"__type": "Pointer",
"className": "Player",
"objectId": "UGAmRVd7Tr"
},
"defenderScore": 25,
"objectId": "HqptXdYmQL",
"updatedAt": "2014-12-05T21:43:01.969Z"
}
]}
I'm reading it into my script like this:
我正在像这样将它读入我的脚本:
var fs = require('fs');
var results = JSON.parse(fs.readFileSync('Game.json', 'utf8'));
resultsis an object but it's not an array.
results是一个对象,但它不是一个数组。
I would like to make it an array so I can iterate through each game, grab the data I need from each game and use it to create a new object that I ultimately save in a .json file.
我想让它成为一个数组,以便我可以遍历每个游戏,从每个游戏中获取我需要的数据并使用它来创建一个新对象,我最终将其保存在 .json 文件中。
I would love for someone to guide me through this entire process but I would be thrilled if someone can just show me how to make an array of games that I can iterate through just to get me started.
我希望有人能指导我完成整个过程,但如果有人能向我展示如何制作一系列我可以迭代的游戏来让我开始,我会很兴奋。
Thank you.
谢谢你。
采纳答案by Neeraj Sharma
You can try Javascript's inbuilt functions like this:
您可以像这样尝试 Javascript 的内置函数:
var fs = require('fs');
var results = JSON.parse(fs.readFileSync('games.json', 'utf8'));
function grabDataFromAGame(elem, index, array) {
// Grab the data from the game object you need
var gameObj = {};
gameObj.challengerScore = elem.challengerScore;
gameObj.defenderScore = elem.defenderScore;
gameObj.id = elem.objectId;
saveGameObjToFile(gameObj);
}
function saveGameObjToFile(gameObj){
var gameFile = fs.openSync('./gameObj-' + gameObj.id + '.json', 'w');
fs.writeSync(gameFile, JSON.stringify(gameObj));
}
results.results.forEach(grabDataFromAGame);
This code generated the following files:
此代码生成以下文件:
~/salesman 542-> node so.js
~/salesman 543->
~/salesman 543->
~/salesman 543-> ll gameObj-*
-rw-r--r-- 1 neerajsharma staff 59B Jun 11 18:56 gameObj-pmiACGwe45.json
-rw-r--r-- 1 neerajsharma staff 59B Jun 11 18:56 gameObj-HqptXdYmQL.json
~/salesman 544-> cat gameObj-pmiACGwe45.json | python -m json.tool
{
"challengerScore": 18,
"defenderScore": 21,
"id": "pmiACGwe45"
}
~/salesman 545->
Note that it is not recommended to use synccalls with Node, because node is single-threaded and your application is blocked till the sync calls are complete.
请注意,不建议对syncNode使用调用,因为 Node 是单线程的,并且您的应用程序会被阻塞,直到同步调用完成。
An example of using forEach can be found here
可以在此处找到使用 forEach 的示例
回答by beautifulcoder
Try:
尝试:
results.results.forEach(function (result) {
console.log(result);
});
You should try to use the async calls. Node.js is really meant for asynchronous non-block I/O.
您应该尝试使用异步调用。Node.js 真正适用于异步非块 I/O。
回答by Muhammad Umer
Your code is very close:
您的代码非常接近:
var results = JSON.parse(fs.readFileSync('Game.json', 'utf8'))['results'];
var results = JSON.parse(fs.readFileSync('Game.json', 'utf8'))['results'];
You get object that has Arrayset as value for key"results".
您获得已Array设置为键“结果”值的对象。
回答by Stephen S
You should be able to access it as follows:
您应该可以按如下方式访问它:
for (var i = 0; i < results.results.length; i++) {
results.results[i].challengerScore; //some game data
}

