I've got an XML-file. After converting it to JSON I want to access some content within. This was possible. However, some variable within the JSON contain a - (minus sign). When I try to access it, Javascript interpret this as a calculation. Is the only way to workaround this to replace all the - signs?
Asked
Active
Viewed 4,216 times
2
Nisse Engström
- 4,738
- 23
- 27
- 42
user6182078
- 55
- 1
- 4
-
Can you some code? – Apr 09 '16 at 19:31
-
JSON **cannot** contain variables. Valid JSON is always single object or array – hindmost Apr 09 '16 at 19:44
-
[Hyphen is not a minus sign](http://theweek.com/articles/460264/youre-using-that-dash-wrong). – Michał Perłakowski Apr 09 '16 at 20:18
2 Answers
2
You can use brackets notation:
yourJson['ab-cd']; // access to 'ab-cd' property that contains '-' sign
isvforall
- 8,768
- 6
- 35
- 50
2
If you want to define or access properties with special characters in them, you need to use string property names:
var obj = {
'some-string-with-hyphens': true,
'another-one': true
};
var another = obj['another-one'];
scott113341
- 109
- 4