How to read JSON data in Drupal 7

I have server 1 that will send JSON data to my server 2 url (Drupal website)

JSON Request Object Example

{"ConfirmationNumber":"344", "E-mailAddress":"EMAIL@ADDRESS.COM", "FirstName":"FIRSTNAME", "LastName":"LASTNAME", "SKU":"XYZ"}

I need to read the above request on the Drupal website, which means server 2 parses the JSON object and executes some business logic. Any quick help really appreciated

Example: http://mydrupalsite.com/services/register

Some external site is sending JSON data to the above URL.

I need to read the JSON content that they posted on my drupal site. This is what I want. Getting / reading data is my first step. Parse is fine, what can we do next.

+4
source share
5 answers
/**
 * Implementation of hook_services_resources().
 */
function yourmodulename_services_resources() {
  return array(
   'yourmodulename' => array(
     'create' => array(
       'help' => 'Retrievs a test',
       'callback' => '_yourmodulename_create',
       'access callback' => '_yourmodulename_access',      
       'args' => array(
         array(
            'name' => 'data',
            'type' => 'struct',
            'description' => 'The note object',
            'source' => 'data',
            'optional' => FALSE, 
         ),
       ),
     ),
   ),
  );
}

/**
 * Callback for creating  resources.
 *
 * @param object $data
 * @return object
 */
function _yourmodulename_create($data) {
return $data;
}

/**
 * Access callback for the note resource.
 *
 * @param string $op
 *  The operation that going to be performed.
 * @param array $args
 *  The arguments that will be passed to the callback.
 * @return bool
 *  Whether access is given or not.
 */
function _yourmodulename_access($op, $args) {
  $access = TRUE;
  return $access;
}
+1

json.

$url = "your request url";
$request = drupal_http_request($url);
$json_response = drupal_json_decode($request->data);
foreach ($json_response as $response_data) {
  //your operation code  
}
+5

Use drupal_json_decode ($ data). You will get a php array. Then use foreach and scroll it to get the values.

$content = drupal_json_decode($data);
foreach($content as $key => $value) {
  // here $value will contain your value. You can perform any business logic with     $value...
}
0
source

If you need a JSON object from a URL, for example {"text": "HelloWorld"}. I recommend using this method:

//Create a path
$mypath = 'http://example.com';
//Create a option
$options = array('query' => array('parametr1' => '1', 'parametr2' => '2'));
//Create url
$url = url($path = $url, $options);
//Create request 
$request = drupal_http_request($url);
//Take response data(A string containing the response body that was received)
$json_response = drupal_json_decode($request->data);
// Varible text return HelloWorld 
$text = $json_response['text'];

Hello

0
source

All Articles