简体   繁体   English

将JSON转换为Javascript数组对象-node.js

[英]Convert JSON to Javascript Array Object - node.js

I don't know any Javascript. 我不懂任何Javascript。 I have a .json file that looks like this: 我有一个.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'));

results is 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. 谢谢。

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的。

Your code is very close: 您的代码非常接近:

var results = JSON.parse(fs.readFileSync('Game.json', 'utf8'))['results'];

You get object that has Array set as value for key "results". 您将获得将Array设置为 “结果”的值的对象。

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 sync calls with Node, because node is single-threaded and your application is blocked till the sync calls are complete. 请注意,不建议对Node使用sync调用,因为node是单线程的,并且在同步调用完成之前,您的应用程序将被阻塞。

An example of using forEach can be found here 可以在此处找到使用forEach的示例

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM