Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

JSON keys with spades 1

Status
Not open for further replies.

newjim

Programmer
Sep 8, 2001
21
CA
Can you put spaces in a JSON key? My JSON object comes from a database so I can't change it.

For example, "first Name" below has a space in it.

var JSON_text =
{
"first Name": "John",
"lastName": "Smith
}
Using eval("JSON_text." + "first Name") or
eval("JSON_text[" + "first Name" + "]")

do not work. JSON is very limited if it can't use keys with spaces in them.

Thanks
 
This is a stab here, but can you use the escape character (%20) for the space?

JSON_text.first%20Name ??


[monkey][snake] <.
 
After looking through a lot of pages and finding no definitive documentation, I don't think spaces are allowed in the keys for a JSON element.

JSON is supposed to be very compatible with XML, XML does not allow spaces in tag names.

As well I saw may examples of keys with _ or - in them where a space would typically go.

[monkey][snake] <.
 
Not sure if there's a restriction, but it does work:

Code:
var obj = {
   "abc": 1,
   "def": 3.5,
   "x y z": 7
};

alert(obj.abc);       // shows 1
alert(obj['abc']);    // shows 1
alert(obj.def);       // shows 3.5
alert(obj['def']);    // shows 3.5
alert(obj['x y z']);  // shows 7

Dan

Coedit Limited - Delivering standards compliant, accessible web solutions

[tt]Dan's Page [blue]@[/blue] Code Couch
[/tt]
 
Yes, this works. To choose the JSON key dynamically, you would have to break the square braces up, like this:
<script language='javascript'>
var JSON_text =
{
"first Name": "John",
"lastName": "Smith"
}
function showData(theDiv)
{
document.getElementById(theDiv).innerHTML = eval("JSON_text['" + theDiv + "']")
}
</script>

<table border='1'>
<tr>
<th><input type='button' name='b1' value='First Name' onclick="showData('first Name')"></th>
<td width='100px'><div id="first Name"></div></td>
</tr>
</table>

Thanks.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top