HTML and CSS Reference
In-Depth Information
EXAMPLE
18.23
1
<script type="text/javascript" src="json2.js">
</script>
<script type="text/javascript">
2
var jsonString = '{"name":"Joe Shmoe", "phone":"415-111-1111"}';
3
var employee=JSON.parse(jsonString);
alert("Name: " + employee.name + "\nPhone: "+ employee.phone);
</script>
EXPLANATION
1
The JavaScript program will use the
json2.js
library.
2
A string is created containing the text that will be parsed by the library's
JSON.parse()
method.
3
The
JSON.parse()
method converts the string, called jsonString, into a JavaScript
object (see Figure 18.23).
Figure 18.23
After adding the json2.js library, Internet Explorer works fine.
Douglas Crockford at JSON.org has provided a set of routines that will convert any
JavaScript data type into a JSON string. Go to
http://www.JSON.org/JSON.js
for a free
download of the most current library for parsing and stringifying JSON objects,
json2.js
.
With this library you can read JSON strings and write them to the server. Example 18.24
demonstrates how to use the
json2.js
library to create a JavaScript object from the text
coming from the JSON file.
The steps are:
1. Make sure the
.json
file is in the correct object format. (The MIME type is
“application/json” and may have to be set in your server so that Firefox does
not read the JSON file as an XML file resulting in a “not well-formed” error.)
2. At the top of your Ajax program add the
<script>
tag
src
attribute to the name of
the JSON library, in this case “json2.js”:
<script type="text/javascript" src="json2.js">
3. In the Ajax program, read the object in as text from the
XMLHttpRequest
object's
responseText
property into a string variable.
4. Use the
JSON.parse()
method to turn the string into a JavaScript object.
5. Use the properties and values of the object to get the information from the
object such as
myObject.name
,
myObject.phone
, and so on.