How to Convert a String to JSON Object in PHP

How to convert a string to JSON object in PHP

What @deceze said is correct, it seems that your JSON is malformed, try this:

{
"Coords": [{
"Accuracy": "30",
"Latitude": "53.2778273",
"Longitude": "-9.0121648",
"Timestamp": "Fri Jun 28 2013 11:43:57 GMT+0100 (IST)"
}, {
"Accuracy": "30",
"Latitude": "53.2778273",
"Longitude": "-9.0121648",
"Timestamp": "Fri Jun 28 2013 11:43:57 GMT+0100 (IST)"
}, {
"Accuracy": "30",
"Latitude": "53.2778273",
"Longitude": "-9.0121648",
"Timestamp": "Fri Jun 28 2013 11:43:57 GMT+0100 (IST)"
}, {
"Accuracy": "30",
"Latitude": "53.2778339",
"Longitude": "-9.0121466",
"Timestamp": "Fri Jun 28 2013 11:45:54 GMT+0100 (IST)"
}, {
"Accuracy": "30",
"Latitude": "53.2778159",
"Longitude": "-9.0121201",
"Timestamp": "Fri Jun 28 2013 11:45:58 GMT+0100 (IST)"
}]
}

Use json_decode to convert String into Object (stdClass) or array: http://php.net/manual/en/function.json-decode.php

[edited]

I did not understand what do you mean by "an official JSON object", but suppose you want to add content to json via PHP and then converts it right back to JSON?

assuming you have the following variable:

$data = '{"Coords":[{"Accuracy":"65","Latitude":"53.277720488429026","Longitude":"-9.012038778269686","Timestamp":"Fri Jul 05 2013 11:59:34 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.277720488429026","Longitude":"-9.012038778269686","Timestamp":"Fri Jul 05 2013 11:59:34 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.27770755361785","Longitude":"-9.011979642121824","Timestamp":"Fri Jul 05 2013 12:02:09 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.27769091555766","Longitude":"-9.012051410095722","Timestamp":"Fri Jul 05 2013 12:02:17 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.27769091555766","Longitude":"-9.012051410095722","Timestamp":"Fri Jul 05 2013 12:02:17 GMT+0100 (IST)"}]}';

You should convert it to Object (stdClass):

$manage = json_decode($data);

But working with stdClass is more complicated than PHP-Array, then try this (use second param with true):

$manage = json_decode($data, true);

This way you can use array functions: http://php.net/manual/en/function.array.php

adding an item:

$manage = json_decode($data, true);

echo 'Before: <br>';
print_r($manage);

$manage['Coords'][] = Array(
'Accuracy' => '90'
'Latitude' => '53.277720488429026'
'Longitude' => '-9.012038778269686'
'Timestamp' => 'Fri Jul 05 2013 11:59:34 GMT+0100 (IST)'
);

echo '<br>After: <br>';
print_r($manage);

remove first item:

$manage = json_decode($data, true);
echo 'Before: <br>';
print_r($manage);
array_shift($manage['Coords']);
echo '<br>After: <br>';
print_r($manage);

any chance you want to save to json to a database or a file:

$data = '{"Coords":[{"Accuracy":"65","Latitude":"53.277720488429026","Longitude":"-9.012038778269686","Timestamp":"Fri Jul 05 2013 11:59:34 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.277720488429026","Longitude":"-9.012038778269686","Timestamp":"Fri Jul 05 2013 11:59:34 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.27770755361785","Longitude":"-9.011979642121824","Timestamp":"Fri Jul 05 2013 12:02:09 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.27769091555766","Longitude":"-9.012051410095722","Timestamp":"Fri Jul 05 2013 12:02:17 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.27769091555766","Longitude":"-9.012051410095722","Timestamp":"Fri Jul 05 2013 12:02:17 GMT+0100 (IST)"}]}';

$manage = json_decode($data, true);

$manage['Coords'][] = Array(
'Accuracy' => '90'
'Latitude' => '53.277720488429026'
'Longitude' => '-9.012038778269686'
'Timestamp' => 'Fri Jul 05 2013 11:59:34 GMT+0100 (IST)'
);

if (($id = fopen('datafile.txt', 'wb'))) {
fwrite($id, json_encode($manage));
fclose($id);
}

I hope I have understood your question.

Good luck.

PHP convert string to object

Please validate your JSON code.

JSON rules

  1. Data is in name/value pairs
  2. Data is separated by commas
  3. Curly braces hold objects - Your file contains no parent object
  4. Square brackets hold arrays
  5. A name/value pair consists of a field name (in double quotes). -
    Your name fields are not in double quotes

Valid JSON code:

    {
"MESSAGE_HEADER": {
"SENDING_APPLICATION": "IQCARE",
"SENDING_FACILITY": 10829,
"RECEIVING_APPLICATION": "IL",
"RECEIVING_FACILITY": 10829,
"MESSAGE_DATETIME": "20170713110000",
"SECURITY": "",
"MESSAGE_TYPE": "ADT^A04",
"PROCESSING_ID": "P"
},
"PATIENT_IDENTIFICATION": {
"EXTERNAL_PATIENT_ID": {
"ID": "110ec58a-a0f2-4ac4-8393-c866d813b8d1",
"IDENTIFIER_TYPE": "GODS_NUMBER",
"ASSIGNING_AUTHORITY": "MPI"
}
}
}

Working PHP example with valid JSON code:

<?php

$json = '
{
"MESSAGE_HEADER": {
"SENDING_APPLICATION": "IQCARE",
"SENDING_FACILITY": 10829,
"RECEIVING_APPLICATION": "IL",
"RECEIVING_FACILITY": 10829,
"MESSAGE_DATETIME": "20170713110000",
"SECURITY": "",
"MESSAGE_TYPE": "ADT^A04",
"PROCESSING_ID": "P"
},
"PATIENT_IDENTIFICATION": {
"EXTERNAL_PATIENT_ID": {
"ID": "110ec58a-a0f2-4ac4-8393-c866d813b8d1",
"IDENTIFIER_TYPE": "GODS_NUMBER",
"ASSIGNING_AUTHORITY": "MPI"
}
}
}
';

$object = json_decode($json);

echo $object->MESSAGE_HEADER->SENDING_APPLICATION;

?>

Convert strings to json in php

You need to use json_decode ("Decodes a JSON string") instead of json_encode ("Returns the JSON representation of a value").

Assuming your input is correct (and the example presented by you is), the return value will be an object representing the JSON data. You can also get the result as an array (see the docs for parameter reference).


EDIT: There must be another problem with your code, please post your complete code.

(My guess would be that you are not checking the returned value but expect json_decode to modify the parameter by reference and only check the parameter variable - that would explain why "nothing happens")

The following works:

(Ideone snippet)

PHP code:

<?php

$json = <<<JSON
[{"target_detail_id":"66351031","first_name":"Dorothy","last_name":"Smith","company":"Active Money Now","sic_code":"","position":"","target":"1300572544","website":"","email":"dorothy@activemoney.com.au","email_status":"","country":"Australia","city":"Broken Hill","postal_code":"2880","address":"Po Box 41","note":""}]
JSON;

$object = json_decode($json);
$array = json_decode($json, true);

var_dump($object);
var_dump($array);

output:

array(1) {
[0]=>
object(stdClass)#1 (15) {
["target_detail_id"]=>
string(8) "66351031"
["first_name"]=>
string(7) "Dorothy"
["last_name"]=>
string(5) "Smith"
["company"]=>
string(16) "Active Money Now"
["sic_code"]=>
string(0) ""
["position"]=>
string(0) ""
["target"]=>
string(10) "1300572544"
["website"]=>
string(0) ""
["email"]=>
string(26) "dorothy@activemoney.com.au"
["email_status"]=>
string(0) ""
["country"]=>
string(9) "Australia"
["city"]=>
string(11) "Broken Hill"
["postal_code"]=>
string(4) "2880"
["address"]=>
string(9) "Po Box 41"
["note"]=>
string(0) ""
}
}
array(1) {
[0]=>
array(15) {
["target_detail_id"]=>
string(8) "66351031"
["first_name"]=>
string(7) "Dorothy"
["last_name"]=>
string(5) "Smith"
["company"]=>
string(16) "Active Money Now"
["sic_code"]=>
string(0) ""
["position"]=>
string(0) ""
["target"]=>
string(10) "1300572544"
["website"]=>
string(0) ""
["email"]=>
string(26) "dorothy@activemoney.com.au"
["email_status"]=>
string(0) ""
["country"]=>
string(9) "Australia"
["city"]=>
string(11) "Broken Hill"
["postal_code"]=>
string(4) "2880"
["address"]=>
string(9) "Po Box 41"
["note"]=>
string(0) ""
}
}

EDIT2:

  1. You don't need quotes around the json_decode parameter, just use

    json_decode($_REQUEST['derulo'], true);

    But this is not what is causing problems (it's just inefficient, php has to parse another variable in a string).

  2. Your php snippet works, so you must be getting wrong data from the query. You can easily check for that with

    var_dump($_REQUEST['derulo']);

    You shouldn't be mixing sending data in both the url and over data, when using a GET request or switch to POST. I'd recommend letting jQuery take care of the serialization of the data, e.g.

    $.ajax({
    type: 'GET',
    url: 'index.php',
    data: {
    'task':'search',
    'wtd':'ul',
    'derulo':JSON.stringify($('#getdbresult').val())
    },
    beforeSend: function(){
    $('.the-modal').html('Updating...');
    },
    success: function(d){
    $('.the-modal').html(d);
    console.log(d);
    }
    });

Php convert string into JSON or an Array

The goal is to turn it into appropriate JSON format so that you can use json_decode. Ill break it down in steps:

  1. remove all \n characters:

    $string = str_replace('\n', '', $string);
  2. remove last comma

    $string = rtrim($string, ',');
  3. add brackets

    $string = "[" . trim($string) . "]";
  4. turn it into PHP array:

    $json = json_decode($string, true);

Result:

$string = ''; //your string
$string = str_replace('\n', '', $string);
$string = rtrim($string, ',');
$string = "[" . trim($string) . "]";
$json = json_decode($string, true);
var_dump($json);

Output:

array (size=3)
0 =>
array (size=6)
'account_id' => string '43z95ujithllc32fn02u8ynef' (length=25)
'email' => string 'mail-noreply@google.com' (length=23)
'id' => string '955xl0q3h9qe0sc11so8cojo2' (length=25)
'name' => string 'Gmail Team' (length=10)
'object' => string 'contact' (length=7)
'phone_numbers' =>
array (size=0)
empty
1 =>
array (size=6)
'account_id' => string '43z95ujithllc32fn02u8ynef' (length=25)
'email' => string 'test-email1@gmail.com' (length=21)
'id' => string '3u4e6i9ka3e7ad4km90nip73u' (length=25)
'name' => string 'Test Account 1' (length=14)
'object' => string 'contact' (length=7)
'phone_numbers' =>
array (size=0)
empty
2 =>
array (size=6)
'account_id' => string '43z95ujithllc32fn02u8ynef' (length=25)
'email' => string 'test-email@gmail.com' (length=20)
'id' => string 'bt3lphmp0g14y82zelpcf0w0r' (length=25)
'name' => string 'Test Account' (length=12)
'object' => string 'contact' (length=7)
'phone_numbers' =>
array (size=0)
empty

Json string conversion to json object

You are trying to decode an array, either specify the specific item within the array, or make it a string.

For instance:

$unBillableArr = '{"id":"123", "to":"+923412268656", "MsgReceivedFrom":"03349433314", "message":"Qwertyy", "recdate":"2017-11-20 19:01:49"}';

$json = json_decode($unBillableArr, true);

// Or

$unBillableArr = ['{"id":"123", "to":"+923412268656", "MsgReceivedFrom":"03349433314", "message":"Qwertyy", "recdate":"2017-11-20 19:01:49"}'];

$json = json_decode($unBillableArr[0], true);

However, given the string you are receiving does not contain valid JSON and you are unable to control what you receive, I have prepared the following that will replace the single quotes in your JSON, and decode each item into an array:

$unBillableArr = ["{'id' : '123','to' : '+923412268656','MsgReceivedFrom' : '03349433314', 'message':'Qwertyy ', 'recdate':'2017-11-20 19:01:49'}"];

// Loop through each JSON string
$jsonObjects = []; // Change this name...
foreach ($unBillableArr as $jsonString) {
$jsonObjects[] = json_decode(str_replace("'", '"', $jsonString), true);
}

print_r($jsonObjects); // Proof it works

Please bear in mind that I would consider this to be a dirty fix. To fix this properly, you should go back to the source and ensure that the JSON they are returning to you is valid.

convert php string to json object

You can use json_decode() php function.

$json_string = '[{"id_piesa":"8","cantitate_piesa":"12","garantie_piesa":false},{"id_piesa":"30","cantitate_piesa":1,"garantie_piesa":true}]';
$array = json_decode( $json_string , TRUE);

print_r( $array);

Output:

Array
(
[0] => Array
(
[id_piesa] => 8
[cantitate_piesa] => 12
[garantie_piesa] =>
)

[1] => Array
(
[id_piesa] => 30
[cantitate_piesa] => 1
[garantie_piesa] => 1
)

)

if you add TRUE as second argument the returned objects will be converted into associative arrays.

Here you can find the complete documentation.

How to convert string response into JSON object?

Try this:-

$curl_response = curl_exec($curl);

function escapeJsonString($value) {
$escapers = array("\'");
$replacements = array("\\/");
$result = str_replace($escapers, $replacements, $value);
return $result;
}

$curl_response = escapeJsonString($curl_response);

$curl_response = json_decode($curl_response,true);

echo '<pre>';print_r($curl_response);

echo $error = json_last_error();

Reference taken:- http://www.pontikis.net/tip/?id=5

The link you found useful is:- https://stackoverflow.com/a/20845642/4248328



Related Topics



Leave a reply



Submit