Search code examples
javascriptjsonjavascript-objects

Attempting to access data from JavaScript .json object with {object}.#text location


I'm attempting to access the text value of a JavaScript .json object with under the location of loggie.stats.Wins. Under the Wins column there are 3 subcategories listed: @category, @abbreviation, and #text. I'm particularly interested in the value of #text, but when I attempt:

console.log(JSON.stringify(loggie.stats.Wins.#text)) 

I receive the error SyntaxError: {app location}\src\App.js: Unknown PrivateName "#text"

I'm assuming there is something about the @ and # tags in a json object I do not understand, but I don't know where to look. I can stringify the whole .Wins object and pull it from there I suppose but I'm guessing there is a less convoluted way to go about it.

EDIT: MisterJojo gave me the solution, I needed to access it as loggie.stats.Wins['#text']. I'm hoping he can point me towards a reading source so I can explain in greater detail how the answer works here.


Solution

  • You can't use the dot notation to access JSON fields with names like that.

    In your example you probably should do loggie.stats.Wins["#text"] instead.

    You can only use the dot notation when your field contains alphanumeric letters only (without space, or special characters with the exception of underscore _), and it must start with an alphabetic character or underscore

    e.g.: valid ones:

    object.fIelD1234
    
    object.field_name
    
    object._abc
    

    invalid:

    object.123abc
    
    object.ab-cd
    

    with special characters you will have to access that field with []

    e.g.

    object['123abc']
    
    object['ab cd']
    
    object['#123a']