PHP get array from string - php

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

Related

Array turn to json using php

need your help on this one...
I'm trying to create a code that will get a .txt file and convert all text content to json.
here's my sample code:
<?php
// make your required checks
$fp = 'SampleMessage01.txt';
// get the contents of file in array
$conents_arr = file($fp, FILE_IGNORE_NEW_LINES);
foreach($conents_arr as $key=>$value)
{
$conents_arr[$key] = rtrim($value, "\r");
}
$json_contents = json_encode($conents_arr, JSON_UNESCAPED_SLASHES);
echo $json_contents;
?>
I already got the result when i tried to echo the $json_contents
["Sample Material 1","tRAINING|ENDING","01/25/2018 9:37:00 AM","639176882315,639176882859","Y,Y","~"]
but when I tried to echo using like this method $json_contents[0]
I only got per character result.
Code
Result
hope you can help me on this one..
thank you
As PHP.net says
"Returns a string containing the JSON representation of the supplied value."
As you are using $json_contents[0] this will return the first char of the json string.
You can do this
$conents_arr[0]
Or convert your json string to PHP array using
$json_array = json_decode($json_contents, true);
echo $json_array[0];
It is happening because $json_contents is a string. It might be json string but it's string so string properties will apply here and hence when you echo $json_contents[0] it gives you first character of the string. You can either decode the encoded json string to object like below:
$json = json_decode($json_contents);
echo $json[0];
or echo it before the json_encode:
echo $conents_arr[0];
$json_contents = json_encode($conents_arr, JSON_UNESCAPED_SLASHES);
json_encode() function takes an array as input and convert it to json string.
echo $json_contents; just print out the string.
if you want to access it you have to decode the JSON string to array.
//this convert array to json string
$json_contents = json_encode($conents_arr, JSON_UNESCAPED_SLASHES);
//this convert json string to an array.
$json_contents = json_decode($json_contents, true);
//now you can access it
echo $json_contents[0];

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);

PHP Serialize($array) without dumping array info a:1:{i:0;s:4.... and so on

Is there anything that i print the string without the array information?
(Without this: a:1:{i:0;s:4011:" ";} )?
The whole array must be in single variable and printed. Foreach doesn't help, neither print(array[0]).
You can use json_encode() which will give you less verbose string representation:
<?php
$a = array('a', 'bb' => 'ccc');
echo json_encode($a);
// outputs {"0":"a","bb":"ccc"}
You can use
echo json_encode($array);
This will print a json encoded string.
For you to decode it you can use
json_decode(json encoded string);
You can see docs of php about json encode and json decode

last parameter array on json_decode

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:

Parse JavaScript from remote server using curl

I need to grab a json-string from this page: https://retracted.com
If you view the source, I json-string starts after var mycarousel_itemList =. I need to parse this string as a correct json-array in my php-script.
How can this be done?
EDIT: I've managed to pull this off using explode, but the method is ugly as heck. Is there no build-in function to translate this json-string to a array?
To clarify: I want the string I grab (which is correct json) to be converted into a php-array.
The JSON in the script block is invalid and needs to be massaged a bit before it can be used in PHP's native json_decode function. Assuming you have already extracted the JSON string from the markup (make sure you exclude the semicolon at the end):
$json = <<< JSON
[ { address: 'Arnegårdsveien 32', … } ]
JSON;
var_dump(
json_decode(
str_replace(
array(
'address:',
'thumb:',
'description:',
'price:',
'id:',
'size:',
'url:',
'\''
),
array(
'"address":',
'"thumb":',
'"description":',
'"price":',
'"id":',
'"size":',
'"url":',
'"'
),
$json
)
,
true
)
);
This will then give an array of arrays of the JSON data (demo).
In other words, the properties have to be double quoted and the values need to be in double quotes as well. If you want an array of stdClass objects instead for the "{}" parts, remove the true.
You can do this either with str_replace as shown above or with a regular expression:
preg_match('
(.+var mycarousel_itemList = ([\[].+);.+function?)smU',
file_get_contents('http://bolig…'),
$match
);
$json = preg_replace(
array('( ([a-z]+)\:)sm', '((\'))'),
array('"$1":', '"'),
$match[1]
);
var_dump(json_decode($json, true));
The above code will fetch the URL, extract the JSON, fix it and convert to PHP (demo).
Once you have your json data, you can use json_decode (PHP >= 5.2) to convert it into a PHP object or array

Categories