Parsing JSON w/ @ at sign symbol in it (arobase)
Asked Answered
S

3

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

Sedition answered 3/8, 2011 at 20:18 Comment(4)
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.Kermitkermy
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.Braswell
because i believe it as been answered multiple times in this forum #1710603Apophyllite
@Aaron Saunders: The question you linked is quite different...Braswell
B
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];
Braswell answered 3/8, 2011 at 20:21 Comment(5)
What is the purpose of the @ symbol inside of a json file? Does it have any added meaning inside of the json context?Legman
@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.Braswell
Quite an old question but it comes up in Google searches. The @ symbol in JSON is JSON-LD (JSON for Linked Data). en.wikipedia.org/wiki/JSON-LDGinoginsberg
@Legman I think it is often used to put it on top of alphabetical sort in order to make it stand out (important metadata, ...)Oakie
The @ symbole is often use when you convert XML to JSON, i.e. the properties of a node will get mapped to @, so <product id="p1"/> will generate a JSON with "@id":"p1"Accentor
A
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.

Anett answered 3/8, 2011 at 20:22 Comment(1)
Correct me if I'm wrong, but I don't think you should use the word "array" here.Cyprio
C
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.

Codicodices answered 3/8, 2011 at 20:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.