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 3,430 times
1
Nisse Engström
- 4,636
- 22
- 26
- 40
user6182078
- 45
- 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
1
You can use brackets notation:
yourJson['ab-cd']; // access to 'ab-cd' property that contains '-' sign
isvforall
- 8,366
- 6
- 34
- 49
0
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
- 89
- 4