This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 5 years ago.
How to write PHP for get data from this.
{"room":[{"single_room":1,"twin_room":3}]}{"total_amount":[{"amount":20899}]}{"travelernum":[{"total":1}]}
I tried like this
$BookingDetail["room"]["single_room"];
but got result like this
Illegal string offset 'room'
and
Illegal string offset 'single_room'
How to solve it.
Try this ... you need to decode the json, you get a PHP object and then you can access each element ..
<?php
$str = '{"room":[{"single_room":1,"twin_room":3}]}{"total_amount":[{"amount":20899}]}{"travelernum":[{"total":1}]}';
$json = json_decode($str);
echo "<pre>";
print_r($json);
echo "</pre>";
echo $json->room->single_room;
By the way, I think your json is invalid. You can check this out at http://jsonlint.com/
The string you are using looks like JSON but it doesn't check out as valid. See JSONLint.com... Editing it to make it valid (single line)...
{"room": [{"single_room": 1, "twin_room": 3}], "total_amount": [{"amount": 20899}], "travelernum": [{"total": 1 }]}
OR (Multi-Line)...
{
"room": [{
"single_room": 1,
"twin_room": 3
}],
"total_amount": [{
"amount": 20899
}],
"travelernum": [{
"total": 1
}]
}
If this is the format all your strings are in, you can manipulate them into valid JSON by first by using...
$original_string = '{"room":[{"single_room":1,"twin_room":3}]}{"total_amount":[{"amount":20899}]}{"travelernum":[{"total":1}]}';
$new_string = str_replace("}{", ",", $original_string); // replace }{ with ,
Once your string is in valid JSON format, converting to a PHP array because rather simple, use something like this...
$BookingDetail = json_decode($new_string, true); //true param gets assoc array
I tested all the code above and it works.See PHP json_decode() function reference for more detail on converting JSON strings to PHP Arrays.
http://php.net/manual/en/function.json-decode.php
Related
This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 6 years ago.
The string looks like this.
string(202)
"{"_id":"2","_rev":"2-2251dd9912477d8a2b91c6fd5ce62faf","_attachments":{"creativecommons.pdf":{"content_type":"text/pdf","revpos":2,"digest":"md5-AyV8c76dsfqfGF1BBdQIIw==","length":280357,"stub":true}}} `
I guess preg_match_all is a way to do it but i do not yet know the syntax for it. Maby there is an other way. Some help would be appreciated.
Your string is a JSON string. "Prettified" it looks like this:
{
"_id": "2",
"_rev": "2-2251dd9912477d8a2b91c6fd5ce62faf",
"_attachments": {
"creativecommons.pdf": {
"content_type": "text/pdf",
"revpos": 2,
"digest": "md5-AyV8c76dsfqfGF1BBdQIIw==",
"length": 280357,
"stub": true
}
}
}
You can use json_decode($JSONstring, true); to make it a multidimensional array:
$decoded = json_decode($JSONstring, true);
$myLengthValue = $decoded['_attachments']['creativecommons.pdf']['length'];
echo $myLengthValue; //Returns 280357
preg_match ought to do it
syntax would be preg_match('/length":(.*),/', $string, $array);
preg_match will put the results into an array, so in this case:
$array[0] should be 'length":280357,;',
$array[1] should be '280357'
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);
Hi i have the following issue where in some instances the json_decode does not work and i get an empty array as follows.
// for test purpose set the inbound enc parameter
$_POST["enc"] = "eyJ0cmFuc2NyaXB0IjoiLSAgICAgICAgICBQYXN0ZWQgdGhlIHRleHQgaW50byBOb3RlcGFkIBMgbm8gc3BlY2lhbCBjaGFyYWN0ZXJzIiwiaWQiOjcwLCJpc0FjdGlvbmVkIjp0cnVlLCJ1c2VyX2lkIjoxLCJ0YXNrX3R5cGVfaWQiOjEsImFjY291bnRfaWQiOjIxLCJhY2NvdW50X25hbWUiOiJURVNUIiwiZXZlbnRfZGF0ZSI6bnVsbH0=";
$decoded = base64_decode($_POST["enc"]);
$ar = (array)json_decode($decoded);
echo "<pre>";
print_r($decoded);
echo "</pre>";
echo "<pre>";
print_r($ar);
echo "</pre>";
$decoded displays as a json string, but $ar is null.
Any help please will be appreciated in helping me with this issue.
You didn't supply the second parameter in json_decode to return as an array, and not an object
// for test purpose set the inbound enc parameter
$_POST["enc"] = "eyJ0cmFuc2NyaXB0IjoiLSAgICAgICAgICBQYXN0ZWQgdGhlIHRleHQgaW50byBOb3RlcGFkIBMgbm8gc3BlY2lhbCBjaGFyYWN0ZXJzIiwiaWQiOjcwLCJpc0FjdGlvbmVkIjp0cnVlLCJ1c2VyX2lkIjoxLCJ0YXNrX3R5cGVfaWQiOjEsImFjY291bnRfaWQiOjIxLCJhY2NvdW50X25hbWUiOiJURVNUIiwiZXZlbnRfZGF0ZSI6bnVsbH0=";
$decoded = base64_decode($_POST["enc"]);
$ar = json_decode($decoded, true); //<-- Now returned as an array, and not an object
echo "<pre>";
print_r($decoded);
echo "</pre>";
echo "<pre>";
print_r($ar);
echo "</pre>";
Output
{"transcript":"- Pasted the text into Notepad no special characters","id":70,"isActioned":true,"user_id":1,"task_type_id":1,"account_id":21,"account_name":"TEST","event_date":null}
The error is in your JSON - oddly in the two spaces between "Notepad" and "no".
It looks like there's a nonstandard character between the spaces. Remove that character and the JSON is valid.
Invalid
{"transcript":"- Pasted the text into Notepad no special characters","id":70,"isActioned":true,"user_id":1,"task_type_id":1,"account_id":21,"account_name":"TEST","event_date":null}
Valid
{"transcript":"- Pasted the text into Notepad no special characters","id":70,"isActioned":true,"user_id":1,"task_type_id":1,"account_id":21,"account_name":"TEST","event_date":null}
In the future, ideally you would use json_encode to build your JSON string. The function will automatically escape any non-valid characters for you.
Taking your code and decoding the Base64 encoded string it turns out you have a CHR(13) ASCII character in your JSON data which is causing the JSON to fail validation according to JSON Lint. Taking that character out results in the JSON parsing correctly.
PHP Fiddle
Decoded JSON data:
{
"transcript": "- Pasted the text into Notepad no special characters",
"id": 70,
"isActioned": true,
"user_id": 1,
"task_type_id": 1,
"account_id": 21,
"account_name": "TEST",
"event_date": null
}
HEX Editor Screenshot:
I am stucked with converting the string of specific format to array. Spliting the string using explode doesn't seems to be the right approach and i am not so good with regular expressions. So my question is how can i convert the following string to array?
Current format of the string
maxWidth: 800,
openEffect: elastic,
closeEffect: elastic,
helpers : {
title : {
type: outside
},
thumbs : {
width : 50,
height : 50
}
}
Desired Array
array(
'maxWidth' => 800,
'openEffect' => 'elastic',
'closeEffect' => 'elastic',
'helpers' => array(
'title' => array('type' => 'outside'),
'thumbs' => array('width' => 50, 'height' => 50)
)
)
Any help would be greatly appreciated.
EDIT BASED ON RESPONSES:
The string looks like a JSON but it is not a JSON. Its just a string input from user in that format. The input will be from normal user so i want to keep it simple. There is minimum chance that the normal user will enter a valid JSON.
The string in your example is almost a valid JSON (JavaScript Object Notation) structure!
Here's what your string would look like as valid JSON
{
"maxWidth": 800,
"openEffect": "elastic",
"closeEffect": "elastic",
"helpers": {
"title": {
"type": "outside"
},
"thumbs": {
"width": 50,
"height": 50
}
}
}
So our approach (as suggested by #WiseGuy) would be to first inject a few characters with preg_replace to Turn your string init into valid JSON:
$str = preg_replace('/\b/' , '"' , $str);
$str = '{' . $str . '}';
The regex above is using the Word Boundaries anchor to add quotation marks around all words. Then we wrap the whole thing in curly braces and voilĂ , we've got a x-language compatible object format.
We can now use a standard function to produce our object:
$objUserConfig = json_decode($str, true);
A good beginners tutorial on JSON here: http://code.drewwilson.com/entry/an-introduction-to-json
Use a linter tool such as http://jsonlint.com/ to validate JSON. I used it to debug your example and convert it into proper JSON for my example.
Your input string looks like a json format. PHP has json_decode() to convert json string to object.
To convert to array, use below code:
json_decode($jsonStr, true);
Refer: http://php.net/manual/en/function.json-decode.php
Edit: I know you are showing the printed output of an array and
not a static representation of a php declared array. This is just an
example of how you might convert it into something that can be parsed
into that array. If php has that ability to do so dynamically (I don't know).
Convert the file, read in $str
In this order, do regex on $str.
Each is global flag.
(?i)([a-z]+) to '$1'
(?i)(?<=[a-z]')\s*:(?=\s*[^{\s]) to =>
(?i)(?<=[a-z]')\s*:\s*{ to => array(
} to )
Finally, $newstr = "array(\n$str\n)"
However, something like this that can be read by a php parser as a static
array. How it gets dynamically interpreted into vars I don't know.
Perl can do this.
i need to extract the exam from this json response using php
cb({"data": [{"map": {"exam": ["e", "x", "a", "m"]}, "words": false, "o": ["exam", "exam", "exam"]}]},150)
The problem here is that the answer is wrapped in a callback function cb() which is not valid JSON. The JSON part is the parameter that is passed to this function (everything between and including {...}). So the first step is to remove this "outer function":
$json = trim($json, 'cb(),150');
$data = json_decode($json, true);
$exam = $json['data'][0]['map']['exam'];
Reference: trim, json_decode, arrays
This only works if the number at the end only consists of 1, 5 or 0. You can either add all digits to the second parameter of trim or use a combination of strripos and substr to chop off everything after }.