admin管理员组

文章数量:1278825

I don't know any Javascript. I have a .json file that looks like this:

{ "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.

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.

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.

I don't know any Javascript. I have a .json file that looks like this:

{ "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.

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.

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.

Share Improve this question asked Jun 12, 2015 at 1:26 MayNotBeMayNotBe 2,1403 gold badges33 silver badges50 bronze badges 4
  • 3 The array is in results.results – Phil Commented Jun 12, 2015 at 1:33
  • "I don't know any Javascript." I remend to read a tutorial then. E.g. developer.mozilla/en-US/docs/Web/JavaScript/Guide/… – Felix Kling Commented Jun 12, 2015 at 2:56
  • Wow you guys! Thanks so much for the answers! They were so helpful and I was able to acplish everything I needed. I'm going to accept @Neeraj Sharma 's answer because it was the most detailed but everyone helped a lot. – MayNotBe Commented Jun 12, 2015 at 19:52
  • @FelixKling agreed 100%. Thanks for the link. I was looking at web tutorials but needed to get rolling for this project. I enjoyed it and will definitely be learning more JS! – MayNotBe Commented Jun 12, 2015 at 19:53
Add a ment  | 

4 Answers 4

Reset to default 1

You can try Javascript's inbuilt functions like this:

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 remended to use sync calls with Node, because node is single-threaded and your application is blocked till the sync calls are plete.

An example of using forEach can be found here

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.

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".

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
}

本文标签: Convert JSON to Javascript Array ObjectnodejsStack Overflow