Json_encode returns json cells as string - php

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

Related

Serialized multidimensional stored in MySQLi does not print past first array

Confusing title, the basics are that I'm saving a fully sorted and ordered multidimensional array from a script and into MySQL. I then, on another page, pull it from the database and unserialize it, and then proceed to print it out with this,
$s = "SELECT * FROM gator_historical_data WHERE channelid = '{$chanid}'";
$r = $link->query($s);
$comboarray = array();
while ($row = mysqli_fetch_assoc($r)) {
$comboarray[] = unserialize($row['dataarray']);
}
foreach ($comboarray as $item) {
$desc = $item['content']['description'];
$title = $item['content']['title'];
$datetime = $item['datetime'];
// ... ^^^ problems getting array data
}
The problem is that it doesn't take the full array from MySQL, only the first entry and thus only prints the first 'array'. So where the returned value from dataarray looks like this (var_dump): http://pastebin.com/raw.php?i=Z0jy55sM the data stored into the unserialized $comboarray only looks like this (var_dump): http://pastebin.com/raw.php?i=Ycwwa924
TL;DR: Pulling a serialized multidimensional array from a database, unserializing and it loses all arrays after the first one.
Any ideas what to do?
The string you've got is a serialized string plus something more at the end that is also a serialized string again and again:
a:3:{s:6:"source";s:25:"World news | The Guardian";s:8:"datetime ...
... story01.htm";}}a:3:{s:6:"source";s:16:"BBC News - World";
^^^
This format is not supported by PHP unserialize, it will only unserialize the first chunk and drop everything at the end.
Instead create one array, serialize it and store that result into the database.
Alternatively you can try to recover for the moment by un-chunking the string, however in case the paste was done right, there are more issues. But on the other hand the paste obvious isn't the done fully correct.

PHP json_decode data format

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/

Json content within json content

I am currently working on a php/html/javascript project and am doing ajax post to a php script which returns json encoded data. Within this json encoded there is some more json encoded data.
Below is how I am json encoding the data
$category[0]['Category'] = "Category 1";
$category[1]['Category'] = "Category 2";
$article['Date'] = "11/11/2012 22:42:00";
$article['Title'] = "This is the title";
$article['Subtitle'] = "This is the subtitle";
$article['Content'] = "This is the content1";
$article['ViaName'] = "SomeSite";
$article['ViaAddress'] = "http://localhost";
$article['SourceName'] = "N/A";
$article['SourceAddress'] = "N/A";
$article['categories'] = json_encode($category);
echo json_encode($article);
The $article that gets json encoded I can access fine when it is returned to the javascript using json.Title, json.Subtitle etc.
But when I try and get the categories it doesn't work.
I've tried using json.categories and this prints out the following:
[{"Category":"Category 1"},{"Category":"Category 2"}]
This looks like its working so when I try and access each individual part it then doesn't work. I've tried json.categories[0].Category and json.categories.Category[0] but it keeps on coming up an undefined.
Thanks for any help you can provide.
If you encode an array with json_encode you got a string. So, in your case, json.categories is a string and not an array.
However, json_encode (and decode) is recursive.
So you should use simply
$article['categories'] = $category;
without encode again.
No wait. You are json encoding an array into a value of another array which will be encoded aswell. You should just do:
$article['categories'] = $category;
Add your category json array to article array to access with article variable
$article['categories'] = $category;

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