Dave's Brain

Browse - Programming Tips - What's an easy way to get started with JSON?

Date: 2008oct5
Keywords: sample, kickstart, tutorial
Warning: Using javaScripts eval() for JSON isn't safe

Q.  What's an easy way to get started with JSON?

A.  JSON is a nice way to represent data.  Especially if you
are going to javaScript.

Here is some PHP that makes a JSON object:

# Helper function function escapeDoubleQuotes($a) { return str_replace('"', '\"', $a); } function makeJson($birthday, $favcolor) { $birthday = escapeDoubleQuotes($birthday); $favcolor = escapeDoubleQuotes($favcolor); print "{\"birthday\":\"$birthday\", \"favcolor\":\"$favcolor\"}\n"; }
This makes:
{"birthday":"1980-10-02", "favcolor":"blue"}
Parse it into a javaScript object like this:
function parseJson(json) { var reply, birthday, favcolor; reply = eval('(' + json + ')'); birthday = reply.birthday; favcolor = reply.favcolor; alert('birthday='+birthday + ' favcolor='+favcolor); }

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.