1

I've some page that gives me kinda of a JSON file/output like this example:

  • Description:

    • 23463232

      • tags
      • appid
    • 35433523

      • tags
      • appid
    • 12345234

      • tags
      • appid

I'm trying to get the tags values, like so description.23463232.tags

Add gives me this error:

SyntaxError: identifier starts immediately after numeric literal


I know that you all vars must be strings started by letters but I can't change that because this file/page is not mine. So, I'd like to know what can I do to retrieve the tags values or if there is some way to change the name of that vars like "23463232" to something else.

1
  • 2
    description['23463232'].tags Commented Apr 4, 2015 at 3:01

2 Answers 2

4

That number is probably a string. You can try using the square bracket syntax for reading JSON like so: description["23463232"]["tags"]

Sign up to request clarification or add additional context in comments.

1 Comment

The number is a string in JSON and the JS property name is equivalent to the same string value.. the square brackets have naught to do with string vs. non-string; but rather a sequence of numbers is not a valid JavaScript identifier. Both description["23463232"] and description[23463232] would work.
3

You can use property accessor to access any property name: description["23463232"].tags

Just for completeness of the answer, if you still need to change the variables, you can do this:

for(var key in description) {
    var value = description[key];
    //copy the value to a new key (_ prepended) then delete the original key.
    description["_"+key] = value;
    delete description[key];
}

Now you can access the values like: description._23463232.tags

3 Comments

The stated reason is misleading. As per JavaScript, 'bare properties' must be valid identifiers. In this case that is not possible (as 1234 is a number, not an identifier) so the alternate form has to be used. The JSON format itself is irrelevant for fixing the JavaScript syntax.
As stated in the question, the json is coming from server and it's not an object literal in javascript. You can use number as property name in javascript but in JSON (serialized as string) it will always be string. I mentioned that since it matters how you access the property description[123] or description["123"]
So since it's not JavaScript (which is where the error is), it's a misleading intro reason. The error is simple: 1234 is not a valid JavaScript identifier. The obj.prop form requires that prop is a valid JavaScript identifier while obj[x] allows x to be any valid JavaScript expression. Nothing inherently to do with strings (and description[23463232] is also valid), just syntax.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.