i have a json string im converting to object with a simple eval(string);
heres the sample of the json string:
var json = @'
"{ description" : { "#cdata-section" : "<some html here>" } }
';
var item = eval('('+json+')');
I am trying to access it like so
item.description.#cdata-section
my problem is that javascript does not like the # in the field name.. is there a way to access it?
Any valid string can be used as a JSON key. The following characters are invalid when used in a JSON key: " (double quote) – It must be escaped. \ (backslash) – It must be used to escape certain characters. all control characters like \n , \t.
A JSON string contains either an array of values, or an object (an associative array of name/value pairs). An array is surrounded by square brackets, [ and ] , and contains a comma-separated list of values. An object is surrounded by curly brackets, { and } , and contains a comma-separated list of name/value pairs.
Use the JavaScript function JSON. stringify() to convert it into a string. const myJSON = JSON. stringify(obj);
item.description['#cdata-section']
Remember that all Javascript objects are just hash tables underneath, so you can always access elements with subscript notation.
Whenever an element name would cause a problem with the dot notation (such as using a variable element name, or one with weird characters, etc.) just use a string instead.
var cdata = item.description["#cdata-section"];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With