简体   繁体   中英

Google javascript - accessing and renaming numeric object names

I imported json data into google scripts with:

var doc = Utilities.jsonParse(txt);

I can access most of the objects like such...

var date = doc.data1.dateTime;
var playerName = doc.data1.playerName;
var playerId = doc.data1.playerID;
var teamNumber = doc.data2.personal.team;

A bunch of objects I need to access have numbers as object names...

doc.data2.personal.team.87397394.otherdata
doc.data2.personal.team.87397395.otherdata
doc.data2.personal.team.87397396.otherdata
doc.data2.personal.team.87397397.otherdata

...but when I try to read the data with...

var teamId = doc.data2.personal.team.87397394;

... I get an error "Missing ; before statement."

I tried this...

var teamId = doc.data2.personal.team[87397394];

... and get "teamId undefined" in the log.

I also tied this with the same result...

var teamId = doc.data2.personal.team[+'6803761'];

I can read in the names as strings very easily with "For In", but can't get to the objects themselves. Every example I've found so far uses the brackets so I'm stumped what to try next.

Thank you! Brian

UPDATE

I used this per your suggestions to get the object name into a variable and using the variable in brackets. No error but var test remains "undefined"...

for(var propertyName in doc.data2.personal.team) {
    // propertyName is what you want
    // you can get the value like this: myObject[propertyName]
    Logger.log (propertyNames);
    var test = doc.data2.personal.team[propertyName];
}

The log shows the object names, as expected...
87397394
87397395
87397396
87397397

I'm thinking it's a bug in Google's implementation. Here is an example if anyone wants to verify it. test will return undefined...

function myFunction1() {
  var txt = UrlFetchApp.fetch("http://www.hersheydigital.com/replays/replays_1.json").getContentText();
  var doc = Utilities.jsonParse(txt);
  for(var propertyName in doc.datablock_battle_result.vehicles) {
      Logger.log (propertyName);
      var test = doc.datablock_battle_result.vehicles[propertyName];
   }
}

The problem seems to be in the Utitlies.jsonParse . The following works fine

var txt = UrlFetchApp.fetch("http://www.hersheydigital.com/replays/replays_1.json").getContentText();
var doc = JSON.parse(txt);
for(var propertyName in doc.datablock_battle_result.vehicles) {
    var vehicle = doc.datablock_battle_result.vehicles[propertyName];
    Logger.log('Vehicle id is ' + propertyName);
    Logger.log('Vehicle value is  ' + JSON.stringify(vehicle));
    break;
}

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.

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