Strings should
use double quotes (JSON also requires that the keys be in double quotes).
The following is a JSON object showing the contents of a shopping cart. It contains two
object literals, fruits and vegetables, each containing a number of items:
CHAPTER 5 n AJAX AND DATA EXCHANGE 114
var shoppingCart = {
"fruits": {
"apples":5,
"apricots":4,
"oranges":6,
"mangos":5
},
"vegetables":{
"celery":2,
"lettuce":1,
"green peppers":5
}
};
To reference the celery element:
shoppingCart.vegetables.celery; // or...
shoppingCart["vegetables"]["celery"];
You??™ll notice that "green peppers" has a space in it. Because it is a string, the space is perfectly
valid. However, when using spaces for member names, just remember that you can??™t use
dot notation to refer to them. Therefore, you have to refer to the property "green peppers"
using bracket notation:
shoppingCart.vegetables["green peppers"]; // or...
shoppingCart["vegetables"]["green peppers"];
Parsers are available for languages such as .NET, PHP, and Java that recognize and can
convert JSON into native objects for those languages. You can find more information on JSON
at the JSON web site: http://www.json.org.
nNote Strings should be enclosed in double quotes ("), not just single quotes ('). While the single quotes
will work when evaluating the code in JavaScript, any attempts to parse the JSON object using a JSON
parser (server side or client side) will likely result in an error.
Pages:
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181