last parameter array on json_decode - php

Hello guys i have this string JSON and I decode it with function php json_decode($var,true)
[{"id":"4","name":"Elis"},{"id":"5","name":"Eilbert"}]
Like result i receive this array
Array( [0] => Array ( [id] => 4 [name] => Elis )
[1] => Array ( [id] => 5 [name] => Eilbert ))1
What is it the last number "1" on the end of the array? why is there? I don't want have it how can i delete it?
On js i pass an array converted with JSON.stringify() and the result is like the first json code.
$user = json_decode($this->input->post('to'),true);
$conv_user_id = array();
foreach ($user as $po) {
$conv_user_id[] = $po['id'];
$conv_user_id[] = $id_user;
}
echo print_r($user);
#explosion phill pointed out to me that my json string is wrapped with [] i pass just an array in js converted it witj JSON.stringify(), wich is the error?

You're misusing print_r():
echo print_r($user);
If you would like to capture the output of print_r(), use the return parameter. When this parameter is set to TRUE, print_r() will return the information rather than print it.
When the return parameter is TRUE, this function will return a string. Otherwise, the return value is TRUE.
... and when you cast boolean TRUE to string you get 1.

Learn more about json_decode — Decodes a JSON string.
Example Common mistakes using json_decode()
<?php
// the following strings are valid JavaScript but not valid JSON
// the name and value must be enclosed in double quotes
// single quotes are not valid
$bad_json = "{ 'bar': 'baz' }";
json_decode($bad_json); // null
// the name must be enclosed in double quotes
$bad_json = '{ bar: "baz" }';
json_decode($bad_json); // null
// trailing commas are not allowed
$bad_json = '{ bar: "baz", }';
json_decode($bad_json); // null
?>
Ref:

Related

I am trying to convert string into array in php as i have string like given below

I had tried explode function but it's not giving an output which i want.
Here is my code and explanation:
{
refresh_token: "xxxx",
access_token: "xxxx",
expires_in: 21600,
}
I have this value as string and i want to convert this refresh_token as key in array and "xxxx" as value in array.
I had tried with explode function but it gives new keys like [0]=>"refresh_token".
explode() is not suited for this job. With that string format, you will need to write a custom function. Assuming the values do not contain commas and the last value in your object always ends with a comma just like the others, something like this will do:
function parse_value_string($string) {
preg_match_all('/([a-z_]+):\s+(.*),/', $string, $matches);
return array_combine($matches[1], array_map(function($val) {
return trim($val, '"');
}, $matches[2]));
}
$test = '{
refresh_token: "xxxx",
access_token: "xxxx",
expires_in: 21600,
}';
$values = parse_value_string($test);
print_r($values);
/*
Array
(
[refresh_token] => xxxx
[access_token] => xxxx
[expires_in] => 21600
)
*/
Demo
Depending on your actual data, you're probably going to run into issues with this approach. Your source string is actually really close to regular JSON. If you drop the comma after the last value and wrap your data keys in quotation marks, you can use PHP's native JSON support to parse it:
$test = '{
"refresh_token": "xxxx",
"access_token": "xxxx",
"expires_in": 21600
}';
$values = json_decode($test, true);
print_r($values);
/*
Array
(
[refresh_token] => xxxx
[access_token] => xxxx
[expires_in] => 21600
)
*/
Demo
So, if you can tweak the source of your string to generate valid JSON instead of this custom string, your life will suddenly become a whole lot easier.
you can use the PHP json_decode function as it is a JSON string format.
For example :
$encodedJson = json_decode('{
refresh_token: "xxxx",
access_token: "xxxx",
expires_in: 21600,
}');
$encodedJson->access_token
will give you the xxxx value
use str_split(); that should work
Unquoted keys in otherwise kosher-PHP json, you should just wrap those in quotes if possible, then you can just cast to an array:
$x = (array) json_decode ( '{
"refresh_token": "xxxx",
"access_token": "xxxx",
"expires_in": 21600,
}' );
If that's not possible higher up in the code, you can just use some string hackery to coerece it:
$x = (array) json_decode( str_replace( [ ' ' , ':' , ',' , '{' , '}' ], [ '', '":', ',"' , '{"' , '"}' ],
'{refresh_token:"xxxx",access_token: "xxxx",expires_in: 21600}' ) );
I didn't actually check this code
Also, this is ugly AF
just use json_decode function, but remember to check the validity of your string, for example in your string the last comma should be deleted and keys should be surrounded by double quotes.

PHP get array from string

I have an array in string given below.
$string="
"Status":true,
"ReVerifiedCount":1,
"ProfilePrefix":"INVTRK"
";
How I can get array from this string same as it exists in string.
<?php
$string='{
"Status":true,
"ReVerifiedCount":1,
"ProfilePrefix":"INVTRK"
}';
$data=json_decode($string,true);
print_r($data);
I formated your string-json the right way. Your double quotes and the missing brackets were creating the main problem as your input was not a valid json.
Output is this:
Array ( [Status] => 1 [ReVerifiedCount] => 1 [ProfilePrefix] => INVTRK )
First your String looks like a json string.
$string='{
"Status":true,
"ReVerifiedCount":1,
"ProfilePrefix":"INVTRK"
}';
This is the correct form.
To parse it use json_decode from PHP
$parsedArray = json_decode($string, true);
Here is a link to the doc : http://php.net/manual/en/function.json-decode.php

Converting array to JSON string when array already contains JSON strings

I have an array that contains a JSON string.
Array
(
[0] => Array
(
[name] => Original
[nutrients] => {"calories":{"value":2500,"operator":2},"protein":{"value":500,"operator":1},"carbs":{"value":200,"operator":0},"fat":{"value":50,"operator":0},"sugar":{"value":1,"operator":2}}
)
[1] => Array
(
[name] => Rest
[nutrients] => {"calories":{"value":5000,"operator":2},"sugar":{"value":10,"operator":2}}
)
)
I want to turn the whole array into a JSON string
echo json_encode($array);
But this throws a \ in front of all quotes
[{"name":"Original","nutrients":"{\"calories\":{\"value\":2500,\"operator\":2},\"protein\":{\"value\":500,\"operator\":1},\"carbs\":{\"value\":200,\"operator\":0},\"fat\":{\"value\":50,\"operator\":0},\"sugar\":{\"value\":1,\"operator\":2}}"},{"name":"Rest","nutrients":"{\"calories\":{\"value\":5000,\"operator\":2},\"sugar\":{\"value\":10,\"operator\":2}}"}]
This problem comes about because the nutrients value is already a JSON string.
How can I convert an array into a JSON string when it already contains JSON strings, while having no slashes in front of the quotes?
Use json_decode to convert 'nutrients' to array.
foreach($array as &$a){
$a['nutrients'] = json_decode($a['nutrients']);
}
Then
echo json_encode($array);
How can I convert an array into a JSON string when it already contains JSON strings, while having no slashes in front of the quotes?
If you want to preserve the JSON values as strings; then, you can't, and you shouldn't be able to!
If your array already contains some JSON values (in which they'll have some quotation marks: ") and you want to encode that array into a JSON string, then the quotation marks must be properly escaped, what you get correctly; otherwise, the entire JSON string will be corrupt because of miss-quotation-mark matches.
That's because the " has a special meaning in JSON, but the \" means the "double quotation mark character" not the special token of "; for example, removing the backslashes from the valid JSON string causes some syntax errors for sure:
$json = '[{"name":"Original","nutrients":"{\"calories\":{\"value\":2500,\"operator\":2},\"protein\":{\"value\":500,\"operator\":1},\"carbs\":{\"value\":200,\"operator\":0},\"fat\":{\"value\":50,\"operator\":0},\"sugar\":{\"value\":1,\"operator\":2}}"},{"name":"Rest","nutrients":"{\"calories\":{\"value\":5000,\"operator\":2},\"sugar\":{\"value\":10,\"operator\":2}}"}]';
$json_noBackslashes = str_replace('\\', '', $json);
$json_decoded = json_decode($json_noBackslashes);
echo json_last_error_msg(); // Syntax error
You should be able to json_decode the json data first, then put it back to the original array. After that, you can encode the whole array again to get the desired output.
foreach ($data as $datum) {
$data['nutrients'] = json_decode($data['nutrients']);
}
json_encode($data);

Can I decode JSON containing PHP code?

Is it possible to have a JSON string containing PHP Code, and to have this string decoded?
For example, this works as it should:
$array = ["page", "is-home", $_SERVER["REQUEST_URI"] == "/"];
var_export($array);
// array (
// 0 => 'page',
// 1 => 'is-home',
// 2 => false,
// )
This, does not work:
$json = '["page", "is-home", $_SERVER["REQUEST_URI"] == "/"]';
$array = json_decode($json); // returns NULL
echo json_last_error_msg(); // Syntax error
The second example will only work if $_SERVER["REQUEST_URI"] == "/" is removed from the json string.
Is there a way to parse this string using json_decode, and if not, are there alternative methods to accomplish this?
Many thanks!
UPDATE
The $_SERVER["REQUEST_URI"] == "/" has to be parsed. I am trying to extend Blade Templating so that I can implement parsed functions such as this:
#add-request('page', 'is-home', $_SERVER["REQUEST_URI"] == '/')
UPDATE #2
To try to simplify the matter, I need to turn a string into an object.
$str = '["page", "is-home", $_SERVER["REQUEST_URI"] == "/"]'; // this is obtained by parsing the top blade extension (not important how)
From the string I need the following array:
$array = ["page", "is-home", true / false ]
Keep in mind that the original string can contain theoretically any PHP object for one of the JSON values.
I think you're on the right track, but instead of trying to "simulate" a decode by putting single-quotes, why not (for your proof of concept) first ENCODE, then 'echo' / 'print' the value that it returns, and then DECODE to see what it returns.
Why don't you use json_encode() to obtain json string??
// create json string by json_encode() from array
$json = json_encode([
"page",
"is-home",
$_SERVER["REQUEST_URI"] == "/"
]);
// decode the encoded string with no error, of course ....
$array = json_decode($json);
As you can clearly see in the output, your first array does not contain any PHP at all.
$array = ["page", "is-home", $_SERVER["REQUEST_URI"] == "/"];
automatically fills $array[2] with the boolean false, not with PHP code.
So, let's assume you can't do such a calculation on the client (in fact, you can do this calculation in javascript as well). So you would have to send it to the server as a json string (properly encoded), decode it, eval it, and post the result back into the array.
$json = '["page", "is-home", "$_SERVER[\"REQUEST_URI\"] == \"/\""]';
$array = json_decode($json);
$array[2]=eval($array[2]);
But please don't do this! It is a big security hole.
Instead, feel free to ask a new question as to how you can do this calculation in javascript as well.
For your case you could do:
$is_home = $_SERVER["REQUEST_URI"] == "/";
$json = '["page", "is-home", '. $is_home .']';
$array = json_decode($json);
That's because you are using a variable in your string which is not parsed. In addition, $_SERVER["REQUEST_URI"] == "/" returns false. Boolean false will be converted to an empty string if it is concatenated to a string.
You should rewrite your code to something like this:
// Is the request URI equal to "/"?
$reqUriTest = ($_SERVER["REQUEST_URI"] == "/");
// If boolean false is converted to a string, it will become an empty string.
// So we need to explicitly use values "true" or "false".
$reqUriStr = ($reqUriTest ? "true" : "false");
// Now we can insert $reqUriStr into the JSON string.
$json = '["page", "is-home", '.$reqUriStr.']';
$array = json_decode($json);

How can I parse json array string to array on php

How can I parse json array string to array on php
'[{"a": "1", "b": "2"}, {"a": "3"}]'
seems json_decode allows parse only objects but not arrays. Should it be manually parsed to array before using json_decode?
Seems problem in string. I get a variable with json, and if I output it, looks like the json is valid
echo($jsonvar); //result [{"title":"Home","id":"/","url":"/"}]
but when I try parse string from the variable, the result is nothing even when string is trimmed
echo('[{"title":"Home","id":"/","url":"/"}]', true); //nice parsed array
echo($jsonvar, true); //nothing
echo(trim($jsonvar, " \t\n\r\0\x0B"), true); //nothing
Pass the true as a second parameter to your json_decode() to parse the json string to array.
$json='[{"a": "1", "b": "2"}, {"a": "3"}]';
$arr= json_decode($json,true);
print_r($arr);
You can get the json into array by using the true flag in json_decode()
<?php
$str = '[{"a": "1", "b": "2"}, {"a": "3"}]';
$arr=json_decode($str,true);
print_r($arr);

Categories