Parsing a JSON file

Ask about general coding issues or problems here.

Moderators: macek, egami, gesf

Post Reply
kladrian
New php-forum User
New php-forum User
Posts: 12
Joined: Thu Aug 14, 2014 1:13 am
Contact:

Re: Parsing a JSON file

Post by kladrian » Thu Aug 14, 2014 10:56 am

Hi

first of all your json is not correct. You can't create an key/value array, that would be an object. So instead of [..] you've to use {}

here the correct json:

Code: Select all

{
    "birthdays": {
        "307843200": "Carla",
        "319507200": "Kyle",
        "1390435200": "Noah"
    }
}
then the code it's easy:

Code: Select all

try{
	$json = json_decode($jsondata);
	if (empty($json)){
		echo "invalid json";
		return;
	}
	$birthday = NULL;
	// try to find Noah's birthday
	foreach ($json->birthdays as $timestamp => $name) {
		if (strtolower($name) == 'noah') {
			$birthday = $timestamp;
			break;
		}
	}

	if (!empty($birthday)) {
		echo "Noah's birthday is " . date('Y/m/d');
	}
	else {
		echo "sorry, can't find Noah's birthday";
	}
}
catch (Exception $ee) {
	echo "failed to parse json file";
}
ask again if you need me to explain it :)

---
kladrian

Post Reply

Who is online

Users browsing this forum: No registered users and 2 guests