How to read JSON object name containing special character?

Asked

Viewed 255 times

3

My JSON file:

JSON nome de objeto com caracter trace

"locomotives" and "vacant" I can read without problems, but when I try to read "vacant" it contains the following error::

inserir a descrição da imagem aqui

that is, because of the character " - ", it is being interpreted as another object! How can I solve this? I’ve researched some things but I haven’t found anything yet.

my JS: inserir a descrição da imagem aqui

thanks in advance!

1 answer

5


Try: console.log(Object.keys(data['vagoes-cadastrar']).length);

In addition, it is possible, for example, to pass palavras chaves (of Javascript, as: for, while, get, typeof) for key names, such as:

obj["for"] = "Simon"; // Funciona bem
console.log(obj.for) //Incrivelmente, funciona também.
//Saída: Simon

Note: according to the book You Don't Know JS, when calling with this syntax: obj["for"], in fact, we are referring to access to the "key", while obj.for, we refer to the property of the object.

"The main difference between the two syntaxes is that the operator . requires a compatible Identifier property name right after it, while the syntax ["." ] can accept basically anyone with UTF-8/EU compliant string as the property name. To reference a property named Super-Fun! for example, you would have to use the access syntax ["Super-Fun!" ], because Super-Fun! is not a valid Identifier property name."

REFERENCE:
1. https://developer.mozilla.org/en-US/docs/Web/JavaScript/A_re-introduction_to_JavaScript#Objects
2. https://github.com/CristianoGil/You-Dont-Know-JS/blob/portuguese-translation/this%20%26%20object%20prototypes/ch3.Md

  • wonder! worked perfectly! thank you very much Taffarel Xavier! Apr!

  • 1

    Don’t forget to vote as your primary answer. Thank you, Ird.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.