Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON and whitespaces in identifiers

Question: The JavaScript code below: records is JSON serialized data. I can access it right away from JavaScript by using for example
alert(records.data[0].Phone);

The problem now is that some bright spark used a whitespace in FirstName and LastName, which means I would have to access it like
alert(records.data[0].Last Name);
Which of course is not possible. Is there any way to access it with the whitespace, like an escape sequence? I already tried omitting the whitespace, or replacing it with underscore. The problem is I get the record, and I have no control over the source.

    var records = {
"data" : [
    {
        "First Name" : "John",
        "Last Name" : "Doe",
        "Email" : "[email protected]",
        "Phone" : "(917) 41-6598",
    },
    {
        "First Name" : "Thomas",
        "Last Name" : "Brown",
        "Email" : "[email protected]",
        "Phone" : "(917) 41-2892",
    },
    {
        "First Name" : "Albert",
        "Last Name" : "Hansen",
        "Email" : "[email protected]",
        "Phone" : "(917) 41-3769",
    }
]};



alert(records.data[0].Email);
alert(records.data[0].Phone);
like image 249
Stefan Steiger Avatar asked Jan 21 '26 01:01

Stefan Steiger


1 Answers

 alert(records.data[0]["Last Name"]);

data["x"] is equivalent to data.x

like image 158
Amarghosh Avatar answered Jan 23 '26 13:01

Amarghosh