Reputation: 6579
I am reading a json object such as this:
var url = "not really important"
var response = UrlFetchApp.fetch(url, {'muteHttpExceptions': true});
var json = response.getContentText();
var data = JSON.parse(json);
var var seeds = data.entities.seeds;
Now the seeds have the values, ton of them so I know that all my code works up until this point. Now my problem is parsing a certain piece of the information that I need. In this specific case I need to get the name of each entrant. Each seed has a 1:1 ratio with an entrant and as such I have to naviagte this API to get it.
If I run the following code Logger.log(seeds[0].mutations.entrants);
I will get the following output:
{745803={isPlaceholder=null, name=My Team Name, participantIds=[827364, 827540, 827994], initialSeedNum=1, id=745803, playerIds={827364=179632, 827540=139681, 827994=268019}}}
As you can see the name
is under object called 745803
. My problem is that that object name changes and I have no idea what it is for each seed. As such, I need to grab the very first result that is listed under entrants as it will always be the entrant that I need. How can I do this? I tried the following but it just comes back as undefined:
seeds[0].mutations.entrants[0].name
Bottom line is, how do I get the first element in the json based object without knowing the name of that element?
Upvotes: 0
Views: 1153
Reputation: 201378
You can retrieve JSON keys using "for in". In this case, you can retrieve it even if the keys are changed. Although I don't know the detailed information of your JSON structure, from your question, following 2 patterns are thought.
Pattern 1 :
var json1 = {
"entrants": {
"745803": {
"isPlaceholder": null,
"name": "My Team Name",
"participantIds": [
827364,
827540,
827994
],
"initialSeedNum": 1,
"id": 745803,
"playerIds": {
"827364": 179632,
"827540": 139681,
"827994": 268019
}
}
}
};
for (var i in json1.entrants){
Logger.log(json1.entrants[i].name)
}
>>> My Team Name
Pattern 2 :
var json2 = {
"entrants": [
{
"745803": {
"isPlaceholder": null,
"name": "My Team Name",
"participantIds": [
827364,
827540,
827994
],
"initialSeedNum": 1,
"id": 745803,
"playerIds": {
"827364": 179632,
"827540": 139681,
"827994": 268019
}
}
}
]
};
for (var i in json2.entrants){
for (var j in json2.entrants[i]){
Logger.log(json2.entrants[i][j].name)
}
}
>>> My Team Name
If I misunderstand your question, I'm sorry.
Upvotes: 1