i have this json file :
{ "moosy": { "id": 39464441, "name": "Moosy", "profileIconId": 558, "summonerLevel": 30, "revisionDate": 1436887737000 } }
Which is generated by an API. Here is my code to get it :
var http = require('http');
var LolApi = require('leagueapi');
var summonerName = 'moosy';
var server = http.createServer(function(req, res) {
res.writeHead(200);
LolApi.init('MY_VERY_PRIVATE_KEY', 'euw');
LolApi.Summoner.getByName(summonerName, function(err, summoner) {
if(!err) {
var profil = JSON.stringify(summoner);
console.log(profil);
res.write(profil);
var summonerId = profil.summonerName.id;
console.log(summonerId);
res.write(summonerId);
}
})
});
server.listen(8080);
And i'd like to extract into different variables the ID, NAME, ProfileIconId and summonerLevel.
I haven't figured out how with JSON.parse, can you help me out ? :) I'm using Node JS.
Thanks !
Go to http://jsonlint.com/ and validate your JSON. You will see that it is invalid. Maybe that is causing you troubles.
Check the below post for an idea.
var summonerName = 'moosy';
var profil = { summonerName : { "id": 39464441, "name": "Moosy", "profileIconId": 558, "summonerLevel": 30, "revisionDate": 1436887737000 } };
ID=profil.summonerName.id;
NAME=profil.summonerName.name;
ProfileIconId=profil.summonerName.profileIconId;
summonerLevel=profil.summonerName.summonerLevel;
When you want to use a string variable (like summonerName
) to access properties of an object, you need to use a different syntax.
Instead of doing this:
var summonerId = profil.summonerName.id;
Do this:
var summonerId = profil[summonerName].id;
The first way expects the object to literally have a property called "summonerName", which does not exist.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.