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)
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);
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With