29

My JSON object evaluates to:

{ "@io": IO, "@type": XXX }

If this variable is called my_json, how do I access the @type value of XXX? I tried my_json.@type, but this is giving errors. Help appreciated. Thanks,

Nick

Christophe Roussy
  • 16,299
  • 4
  • 85
  • 85
user823596
  • 341
  • 1
  • 6
  • 8
  • My first inclination would be to do a string replace on your the HTTP response before parsing it. Maybe replace all instances of "@" with "at_" or something. – Joshua Carmody Aug 03 '11 at 20:22
  • 3
    I am not understanding why this question got voted down, and since many people wonder how to access an object property or method which has odd naming, or when they only have a var containing the property name in a string, I will upvote. – JAAulde Aug 03 '11 at 20:26
  • because i believe it as been answered multiple times in this forum http://stackoverflow.com/questions/1710103/accessing-json-fields-with-weird-characters – Aaron Saunders Aug 04 '11 at 03:39
  • @Aaron Saunders: The question you linked is quite different... – JAAulde Aug 05 '11 at 04:23

3 Answers3

44

Use square bracket notation with a string:

var XXXValue = my_json['@type'];

The same can be used when you have a property name in a variable. Using your same example:

var propertyName = '@type';
var XXXValue = my_json[propertyName];
JAAulde
  • 19,250
  • 5
  • 52
  • 63
  • 1
    What is the purpose of the @ symbol inside of a json file? Does it have any added meaning inside of the json context? – boulder_ruby Jul 26 '12 at 21:23
  • 1
    @David in a string such as it is, it has no specific meaning in any context (JSON, JS, etc) within the question. I have no idea why the OP has keys named like that, but it isn't of any significance in the technologies discussed. – JAAulde Jul 27 '12 at 13:20
  • 6
    Quite an old question but it comes up in Google searches. The @ symbol in JSON is JSON-LD (JSON for Linked Data). http://en.wikipedia.org/wiki/JSON-LD – smoore4 Mar 13 '15 at 08:58
  • 1
    @boulder_ruby I think it is often used to put it on top of alphabetical sort in order to make it stand out (important metadata, ...) – Christophe Roussy Jun 10 '16 at 09:10
  • 2
    The @ symbole is often use when you convert XML to JSON, i.e. the properties of a node will get mapped to @, so will generate a JSON with "@id":"p1" – Philippe Lavoie Feb 14 '20 at 17:03
11

As you've discovered, you can't use an @ symbol in a Javascript variable name, my_json.@type is invalid.

The good news for you is that you can access your variables as array subscripts. You would do it like this:

my_json["@type"]

Hope that helps.

Spudley
  • 166,037
  • 39
  • 233
  • 307
1

If it ends up evaluating you can take the object and probably grab it by the key.

ie obj["@type"]. But something does seem a bit off.

ek_ny
  • 10,153
  • 6
  • 47
  • 60