I have JSON string in MySQL database like this
{
"string1": {
"substring1": 1234
},
"string2": {
"substring2": "substring2.1",
"substring3": "substring3.1",
"substring4": {
"substring4.1": 1234,
"substring4.2": 1234,
"substring4.3": 1234
}
}
}
I put those data from MySQL into $string, then I decode it with this function
$json_a = json_decode($string,true);
echo $json_a['string1']['substring1'];
But the result is nothing.
Then I tried to change the $string into
$string = '{"string1":{"substring1":1234},"string2":{"substring2":"substring2.1","substring3":"substring3.1","substring4":{"substring4.1":1234,"substring4.2":1234,"substring4.3":1234}}}';
Next, I use the same function as above and works fine.
Is there any specific things we should do before decode it from mysql?
Thank you
The outer layer of the data you have is not an array, in fact you don't have any arrays in the data at all. Don't use [0] in your PHP.
Access your index with
echo $json_a['string1']['substring1'];
Related
I have a problem when returning a row from database that has a column type TEXT(in this case, column "details") which contains an array of JSON objects. Example:
{
productid: 1
shopid: 1
title: 'Product 1'
--> details: [{"name":"Brand name","value":"Brand value"},{"name":"Color","value":"blue"}]
. . .
}
Data inserted into database in columns of type TEXT are inserted like addslashes(json_encode($array_or_object)) to safely escape before insert.
When returning data, columns of type TEXT by function json_decode() and returned with no problem. Problem occurs when someone tries using single ' and double quotes " in details. Example:
details: [{"name":"\\\"test123\\\"","value":"\\\"test\\\" \\'test\\' \\\"test \\' test \\' t\\\"est"}]
Returned value looks like:
"details": [
{
"name": "\\\"test123\\\"",
"value": "\\\"test\\\" \\'test\\' \\\"test \\' test \\' t\\\"est"
}
],
I have more than one way of storing JSON data in database (as object, array of objects, array of arrays of objects,...), and I need a way to escape these backslashes.
Using stripslashes() on the string before using json_decode() does not work, it breaks the JSON.
Creating a recursive function works, but is not as pretty as I would like it to be. Example:
function decode_json($json) {
if (empty($json)) {
return $json;
}
if (is_string($json)) {
$json = json_decode($json, true);
}
foreach ($json as $key => $value) {
if (is_array($value)) {
$json[$key] = decode_json($value);
continue;
}
$json[$key] = stripslashes($value);
}
return $json;
}
Any help is appreciated.
json_encode already escape your string, you don't need to use addslashes()
Example:
$var = ["value" => "test'\""];
print_r(json_encode($var));
Result:
{"value":"test'\""}
And will be better to use PDO with bind parameters: https://www.php.net/manual/en/pdostatement.bindparam.php
and what exactly is the point of using a database, when storing the raw JSON?
decode first, then escape the values to insert - else you'll also escape all of the JSON delimiters,
which might subsequently cripple the whole input string and render it F.U.B.A.R.
PS: PDOStatement still requires PDO::quote() to escape the input properly.
i am trying to retrieve the value of array via post in php script.
var data = [];
table.rows({ selected: true }).every(function(index){
// Get and store row ID
data.push(this.data()[0]); //create a 1 dimensional array
});
//send data via ajax
$.ajax({
url: '/...../...',
type: 'POST',
data: {userid:data},
dataType: 'json',
In my PHP script so far I am unable to decode the array. Have tried many ways
$myArray = $_REQUEST['userid'];
foreach ($arr as $value) {
$userid= $value; //for now just trying to read single item
}
I have tried print_r($myArray ); this sucessfully prints array contents to screen.
I am trying to retrieve the values for processing! Kindly point me in the right direction
I don't think that PHP would recognise the array that you've called "data" as being an array. Couldn't you turn the data from your table rows into values in a JavaScript object, encode it as a JSON string, then post that to your PHP script and use json_decode($_POST["userid"]) on the PHP end to convert it into a PHP array.
The object you are posting to PHP isn't in particular a jQuery object. Instead it is an JSON object or rather a JSON string. I guess you can't read that object the way you would read an regular array in PHP.
You might want to try to decode the string with json_decode(). With true as an function argument, it will return an php array as suggested in this stackoverflow answer https://stackoverflow.com/a/6964549/6710876
$phpArray = json_decode($myArray, true);
Documentation of json_decode(): http://php.net/manual/en/function.json-decode.php
simply use:
echo json_encode($myArray);
You're foreach is looping $arr, which doesn't exist. Your array is being set to $myArray, so use that in your for.
$myArray = $_REQUEST['userid'];
foreach ($myArray as $value) {
$userid= $value; //for now just trying to read single item
}
I believe you should also be able to find your values in $_POST
According to your var_dump :
array(1) { ["userid"]=> string(21) "assssssss,camo,castor" }
and if we assume "assssssss,camo,castor" are 3 different usernames.
You should use this:
$userids=explode(",",$myArray->userid);
foreach($userids as $userid){
// use $userid
}
I am trying to convert this JSON string into a PHP array. The JSON string is stored in my database and I have already retrieved it.
{
"users": "user1, user2"
}
I need to convert the above JSON string into an array like the following but dynamically.
$myArray = array("user1", "user2")
This is my code:
$row = mysqli_fetch_array($result);
$json = $row['json'];
$decode = json_decode($json);
$list = $decode->users;
$myArray = explode(',', $list);
This code doesn't work in my program but when I print the array with print_r it looks identical to if I print $myArray from the nondynamic string. This is a concern because the nondynamic string works.
The separator between the usernames is comma+space, you're just using comma when you explode, so the second and following usernames are getting a space at the beginning. Try:
$myArray = explode(', ', $list);
I recommend that you change the JSON structure so you store an actual array, rather than a comma-separated list.
{
"users": ["user1", "user2"]
}
Even better would be to change your database structure so the users are in a real table, rather than being wrapped in JSON. This would allow you to perform queries that search for users easily and efficiently.
I have a problem to get the value from json data inside array when the data is more than one.
When my data only one like this:
$mydata='[{"firstName":"Ana","height":5.3}]';
I can just access the height of Ana by substring-ing it first and the decode it, like this:
$mydata= substr($mydata, 1, -1);
$obj = json_decode($mydata);
print $obj->{'height'};
The problem is when the data look like this:
$mydata='[{"firstName":"Ana","height":5.3},{"firstName":"Taylor","height":5.11}]';
How can I get the height of Ana?
print $obj->{0}->{'height'}; //doesn't work.
Please help. Thankyou in advance.
use json_decode
$b_arr=json_decode($mydata,true);
$b_arr[0]['height'];//0 is index for array
You can convert with json_decode and iterate through your array to get your specific data:
<?php
$mydata='[{"firstName":"Ana","height":5.3},{"firstName":"George","height":7.3}]';
$json = json_decode($mydata, true);
foreach($json as $key => $value) {
if($value['firstName'] == 'Ana') {
echo $value['height'];
break;
}
}
?>
My JSON looks like this. How do I get a specific field, e.g. "title" or "url"?
{
"status":1,
"list":
{
"204216523":
{"item_id":"204216523",
"title":"title1",
"url":"url1",
},
"203886655":
{"item_id":"203886655",
"title":"titl2",
"url":"url2",
}
},"since":1344188496,
"complete":1
}
I know $result = json_decode($input, true); should be used to get parsable data in $result, but how do I get individual fields out of $result? I need to run through all the members (2 in this case) and get a field out of it.
json_decode() converts JSON data into an associative array. So to get title & url out of your data,
foreach ($result['list'] as $key => $value) {
echo $value['title'].','.$value['url'];
}
echo $result['list']['204216523']['item_id']; // prints 204216523
json_decode() translates your JSON data into an array. Treat it as an associative array because that's what it is.