Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send object using json

Tags:

json

php

Is there a recommended way of sending an object using json between a server and a client ? Should I use only lower case for properties, should I use an object or an array ?

Update: this question came to me because by default php is encoding an associative array as an object ( after you decode it)

like image 317
johnlemon Avatar asked May 31 '11 15:05

johnlemon


2 Answers

You should make an array, then use PHP's json_encode method. It doesn't matter if the values are uppercase or lower case.

$a = array(
  'Test' => 42,
  'example' => 'Testing'
);

echo json_encode($a); // {"Test":42,"example":"Testing"}

When decoding in PHP, pass true as the 2nd parameter to json_decode to convert objects to arrays.

$data = json_decode($json, true);
like image 148
Rocket Hazmat Avatar answered Sep 27 '22 18:09

Rocket Hazmat


Both these things are entirely up to you.

The casing of your property names is a coding style matter. It really doesn't matter as long as you are consistent -- your project should have fixed standards on this type of thing. If you haven't picked your standards yet, my advice is to go for readability, which usually means lower case or camel-case. I'd avoid upper case, and I'd also avoid using hyphens or underscores, but it is entirely up to you.

As for the choice between objects or arrays, that comes down to what is best suited to the data in question. If it needs named keys, then use an JSON object (ie with curly braces and key:value pairs {'key':'value','key2':'value2'}); if it doesn't, then use an JSON array (ie with square brackets and just values ['value1','value2']). The choice is entirely down to how the data needs to be structured: both are perfectly valid in JSON and neither is better than the other; just used for different purposes.

(PHP, of course, doesn't differentiate -- both keyed and indexed data are stored in PHP arrays, so from the PHP side it makes absolutely no difference).

like image 22
Spudley Avatar answered Sep 27 '22 17:09

Spudley