PHP json_decode data format - php

my json data that names are between ("") is working as following.
var_dump(json_decode('{"a":"foo","b":"bar"}', true));
but names are not between ("") is not working:
var_dump(json_decode('{a:"foo",b:"bar"}', true)) ;
my json data is coming from another server like this:
{a:"foo",b:"bar"}
and that json created by php with json_encode.
$rows = array();
while($r = mysqli_fetch_assoc($sql)) {
$rows[] = $r;
}
return json_encode($rows)
but json_decode returning NULL for this object.

Looks like you will have to modify the string before parsing it because that isn't valid JSON. You can check it with a site like this.
http://jsonlint.com/

Related

Json_encode returns json cells as string

I've got a database structure like this.
I'm willing to get row as a json object for Json.net.
My php code is this
$check_query = mysqli_query($conn, "select * from users where name = '$name' and password = '$pass'");
$rows = array();
while($r = mysqli_fetch_assoc($get_query)) {
$rows[] = $r;
}
if(count($rows) > 0) {
echo json_encode($rows[0]);
}
I'm getting json as this.
{"unique_id":"pcg9sy26","name":"w","password":"w","mail":"alpsavrum#gmail.com","age":18,"locale":"Turkey","city":"Istanbul","subscriptions":"[\"electronics\", \"vacations\"]","history":null,"token":"12562f39b990da0433d7be71992ed634"}
As you can see, subscriptions value is string. I need it to be array as it seems.
{"unique_id":"pcg9sy26","name":"w","password":"w","mail":"alpsavrum#gmail.com","age":18,"locale":"Turkey","city":"Istanbul","subscriptions":[\"electronics\", \"vacations\"],"history":null,"token":"12562f39b990da0433d7be71992ed634"}
Is there any way to achieve this. ?
Thanks a lot !
The way you're retrieving that data is giving you the JSON value as a string. Storing it as JSON in the database is a good idea if it's actually JSON data, but the mysqli driver will not automatically de-serialize it for you. If you want that sort of behaviour you'll need to use an ORM.
When you're having trouble with double encoding, check with var_dump to see what you're actually working with. That would reveal the subscriptions key contains a JSON string, not an array as expected.
What you'll have to do is manually de-serialize it prior to JSON encoding:
if (isset($r['subscriptions'])) {
$r['subscriptions'] = json_decode($r['subscriptions']);
}
$rows[] = $r;
You will need to do this for any and all JSON encoded fields your results might have.
This way you're JSON encoding a proper PHP data structure and not one that's part PHP and part JSON string.
Try json decode function in whatever language you are reading it.
Decode the JSON response and then print it

PHP json_Encode an array of json_encode-ed arrays

Im not sure what is happening, but if i do
json_encode()
On a single array, i get valid json, but if i do something like
$ar['key'] = "name";
$array[] = json_encode($ar);
$json = json_encode($array);
It will return invalid json like so:
["{"key":"name"}"]
The expected outcome is
[{"key":"name"}]
I have searched for hours trying to find what is going on.
Due to lack of desired outcome, I can only assume you are trying to get a multidimensional array.
The correct way to achieve this would be to build an array of arrays, and then json_encode the parent array.
$data = array();
$data['fruits'] = array('apple','banana','cherry');
$data['animals'] = array('dog', 'elephant');
$json = json_encode($data);
Following this code, $json will have the following value
{"fruits":["apple","banana","cherry"],"animals":["dog","elephant"]}
It could then be parsed properly by javascript using jQuery.parseJSON()
Just json_encode the entire array.
$ar['key'] = "name";
$json = json_encode($ar);
json_encode returns a string, and json encoding a string will return a string.
Also it's json_encode, not $json_encode

Passing PHP array to Javascript via GET

I'm trying to pass an array to Javascript after it has sent a GET request to PHP.
Sending and retrieving the data works perfectly but I couldn't find anything about passing the data back as an array like this:
<?php
$result = mysql_query('blablabla');
//converting $result to an array?
echo $result_as_javascript_array;
?>
<script>
$('result').innerHTML = httpGet.responseText
</script>
Convert the data you get from MySQL to JSON. First build a "normal" PHP array as you would normally do, then pass it through the json_encode() function and return it.
On the client you have to parse the JSON string into a JS array or object. See this SO question for details: Parse JSON in JavaScript?
And please use something else for accessing MySQL. The extension you are using is basically obsolete: http://si1.php.net/manual/en/faq.databases.php#faq.databases.mysql.deprecated
you should use json_encode, which works fine, when directly assigning output to a javascript variable
<?php
$result = mysql_query('blablabla');
//first convert result to an associative array
$myarray = array();
while($fetch = mysql_fetch_assoc($result)){
$myarray[]=$fetch;
}
//converting $result to an array?
echo "<script>";
echo "var myArray = ".json_encode($myarray).";";
echo "</script>";
?>
<script>
//now you can use myArray global javascript variable
$('result').innerHTML = myArray.join(",");
</script>
You are looking for json_encode.
Use json_encode like this:
<?php
$result = mysql_query('blablabla');
//converting $result to an array?
echo json_encode($result);
?>
You probably won't want to put the response text right into the innerHTML of your element though unless you are wanting to display the json text in the element.
$arr = array();
while ($row = mysql_fetch_array($result)) {
$arr[] = $row;
}
echo $arr;
However, mysql_ is deprecated, use mysqli instead.
If you want to pass it as JSON, use this:
echo json_encode($arr);

Encoding a SELECT statement as JSON, iOS issues

I am trying to JSON encode the results of my SQL SELECT statement using PHP and am unsure if I am formatting my array correctly before encoding.
My PHP code is:
$stmt = $this->db->prepare('SELECT CLINIC.clinic_name AS "clinicname" FROM CLINIC ORDER BY CLINIC.clinic_name ASC');
$stmt->execute();
$stmt->bind_result($clinicname);
$test = array();
while($stmt->fetch()){
$tempArray = array('clinicname' => $clinicname);
array_push($test, $tempArray);
}
$stmt->close();
// Return clinics, encoded with JSON
header('Content-type: application/json');
$json = json_encode($test);
echo $json;
The result of this array creation and encoding is:
[{"clinicname":"Bangor"},{"clinicname":"Belfast"},{"clinicname":"Crumlin"},{"clinicname":"Londonderry"}]
So I have an array of arrays.
Will this be okay for sending as JSON? All the examples I see seem to be a single array. Am I correct so far?
And then, regarding iOS, will the received object be a NSDictionary or an NSArray?
Any help or feedback on the above would be greatly received.
Matt.
Yes, your JSON is properly formatted. Next time you can use a JSON validator to check.
Also, some details on json_encoding.
A [] represents an array and {} represents an object.
In iOS, if this is the result from an http request, it will be of type NSString, and then need to be parsed by something like:
http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSJSONSerialization_Class/Reference/Reference.html
which then converts it to NSArray, NSDictionary NSString, etc.
Yes, you can send an array of arrays, and you can acces like the follow way:
$response = json_decode($response,true);
foreach ($response as $resp)
{
echo "<br>";
print_r($resp);
}
json example:
[{"id":"38","first_name":"prueba","second_name":"example","first_surname":"prueba","second_surname":"GONZALEZ","email":"x#x.net","network_login":"x.x","pos_name":"x x","position":"1","active":"1"},{"vhur":"292","first_name":"c","second_name":"example","first_surname":"example","second_surname":null,"email":"example#example.com","network_login":"example.example","pos_name":"example example","position":"2","active":"1"}]

PHP, JSON, and MySQL

What is the easiest way to retrieve data from the database, and convert the data to a JSON String?
Is there any kind of helper class? or am I supposed to loop through the columns in my dataset to create the JSON string?
You can use the json_encode function to convert a native PHP array or stdClass object to it's corresponding JSON representation:
$result = $db->query('SOME QUERY');
$set = array();
if($result->num_rows) {
while($row = $result->fetch_array()) {
$set[] = $row;
}
}
echo json_encode($set);
Make an array from mySQL, and json_encode() it
Yes, use PHP's functions to handle JSON encoding.
Here's an example I got from this SO question:
$sth = mysql_query("SELECT ...");
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
print json_encode($rows);
Have you seen the json_encode() function? It takes an array as input and outputs JSON. So the most basic would be a two-dimensional array representing your table as input to json_encode
If you use the json_encode function then you're depending on somebody else's interpretation of the right way to format the json. Which means that you might come out with weird json, or have to contort your classes in evil ways to make the json come out right.
Just something to think about.

Categories