json fieldnames spaces

Lopoc picture Lopoc · Apr 19, 2011 · Viewed 22.6k times · Source

I've such a json structure:

info:
{
First Name: "Robert",
Last Name: "Smith"
}

I'm tring to point to data with javascript using something like: "info.First Name" I know it's incorrect. How can I retrieve those information from the structure I have?

thank

Answer

Andy E picture Andy E · Apr 19, 2011

That's not valid JSON. JSON is a data transport format that requires field names to be string delimited with double quotes, e.g.

{
    "info" : {
        "First Name": "Robert",
        "Last Name": "Smith"
    }
}

After parsing, you can then use obj.info["First Name"] to access the First Name field.

What you have is a JS object literal (that's still invalid), but you can apply the same technique (stringify the property names) to reach the same end goal.