JSON
makes dealing with data in your app exceptionally easy and manageable. The best part about JSON
is you can look at it and understand it. It’s not like the confusing spaghetti DOM that you get with XML, it’s a lean minimal representation of your data. If you’re dealing with chunks of data in your app, you want to be using JSON
.
So while your app will happily eat up all the
JSON
you can throw at it, you still need to make it in the first place – and/or have a server side app that is capable of reading it. If, like me, you use PHP to handle things on a server then things are pretty straightforward. You can use PHP’s
json_encode
and
json_decode
functions. Encode will take your arrays, or objects, and create a
JSON
string of your data. While decode will take a
JSON
string, sent from your app, and turn it into an array or object.
Using PHP’s JSON encode function to create JSON from an array
Let’s consider a situation where your app is requesting some details. It might make a request to your api to get information about a user.
From an app you might make this request:
Over on the server let’s assume there is some code that retrieves user 18’s details from a database, returning the row as an array. If you’re building an associative array from your database query the row could look like this:
3 | "first_name" => "Dwayne" , |
4 | "last_name" => "Hicks" , |
5 | "email" => "dwaynehicks@usssulaco.com" |
To convert this array to a JSON
string that an app could use you just need to run it through PHP’s json_encode
function.
1 | $output = json_encode( $row ); |
Note: this assumes that your database row is contained within the variable, $row
;
Which results in a JSON
formatted string:
1 | { "id" :18, "first_name" : "Dwayne" , "last_name" : "Hicks" , "email" : "dwaynehicks@usssulaco.com" } |
You can then take this JSON
string in your app and extract the necessary data.
Generating JSON for a web app? Don’t forget JSONp
If you’re going to be using JSON
in a web app you may need to consider JSONp
, which allows you to make a cross-domain request if you JSON
is being created on another domain. JSONp
is JSON
with a custom callback function wrapped around it. ReturningJSONp
is very simple, you just need to pass your JSON
resource the callback parameter and wrap the JSON
in its value.
Using the same example as above, from your app you would make the request but with a callback parameter:
1 | GET /api/users/18?jsonp=callback |
When generating your JSON
you just need to wrap the string in the callback response:
1 | $output = $_GET [ 'jsonp' ] . '(' . json_encode( $row ) . ')' ; |
Which would result the following JSON
string:
1 | callback({ "id" :18, "first_name" : "Dwayne" , "last_name" : "Hicks" , "email" : "samcroft@usssulaco.com" }) |
For best practice, check whether or not there is a JSONp
callback parameter and serve the necessary format of JSON
:
1 | $callback = $_GET [ 'jsonp' ]; |
2 | $output = json_encode( $row ); |
5 | echo $callback . '(' . $output . ')' ; |
That covers creating JSON
for you app. Now let’s look at dealing with JSON
, submitted from your app to your server for processing.
Using PHP’s JSON decode function to create an object or array from a JSON string
Submitting a JSON
formatted string from your app to your web server is a great way to transmit data. PHP’s json_decode
function takes a JSON
string and converts it to an object (by default) or an array, making each attribute easy to handle.
Going back to our fictional app again, let’s consider how a new user might be created. You might make the following request to submit some new user data to your server:
2 | { "first_name" : "William" , "last_name" : "Hudson" , "email" : "williamhudson@usssulaco.com" } |
Creating an object from the submitted JSON
Using json_decode
is as simple as json_encode
:
1 | $request = file_get_contents ( 'php://input' ); |
3 | $input = json_decode( $request ); |
Note: I am using php://input, a read-only stream, instead of PHP_POST variables. This is because the POST’ed data was not submitted as a key=>value pair (unlike normal form submissions). This method takes all of the raw submitted data in one chunk making it ideal for use with JSON
as we need it all as one string before breaking it down.
By default json_decode
creates an object. The result of the above would be as follows:
1 | object(stdClass)#1 (3) { |
2 | [ "first_name" ] => string(4) "William" |
3 | [ "last_name" ] => string(5) "Hudson" |
4 | [ "email" ] => string(22) "williamhudson@usssulaco.com" |
You can access each attribute as you would any other object property:
1 | $firstName = $input ->first_name; |
Or iterate through the object:
1 | foreach ( $input as $key => $value ) { |
2 | echo $key . ' = ' . $value ; |
If you prefer to work with arrays, you can create an associative array of the JSON
key=>value pairs by passing a second parameter, true
, to the json_decode
function. Like so:
1 | $request = file_get_contents ( 'php://input' ); |
3 | $input = json_decode( $request , true); |
Which would result in the following array:
2 | [ "first_name" ] => string(4) "William" |
3 | [ "last_name" ] => string(5) "Hudson" |
4 | [ "email" ] => string(22) "williamhudson@usssulaco.com" |
You can access each attribute as you would any other array value:
1 | $firstName = $input [ 'first_name' ]; |
And there we go. Creating JSON
data strings for an app to request, or converting JSON
strings submitted from an app, couldn’t be simpler.
Comments
Post a Comment