Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing Json fields with weird characters

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?

like image 599
Will Avatar asked Nov 10 '09 18:11

Will


People also ask

Can JSON key have special characters?

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.

What is a string in JSON?

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.

Which JavaScript method converts JSON to a JavaScript value?

Use the JavaScript function JSON. stringify() to convert it into a string. const myJSON = JSON. stringify(obj);


2 Answers

item.description['#cdata-section']
like image 54
Joseph Bui Avatar answered Oct 19 '22 23:10

Joseph Bui


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"];
like image 36
friedo Avatar answered Oct 20 '22 00:10

friedo