Dave's Brain

Browse - programming tips - easy json

Date: 2008oct5
Keywords: sample, kickstart, tutorial

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);
	}
What this info useful to you? You can donate to say thanks

Add a comment

Sign in to add a comment
Copyright © 2008-2010, 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.