I have a json output from a database quesry that looks as follows:
[
{
"name": 1,
"value": "27.18161362"
},
{
"name": 2,
"value": "323.69645128"
},
{
"name": 3,
"value": "23.16249181"
}
]
I am trying to plug this into a script that will make charts from the data. The script requires the data to be in the following format:
{"script":
[
{"name":"1","value":27.18161362},
{"name":"2","value":323.69645128},
{"name":"3","value":23.16249181}
]
}
If it is not formatted in this way, the script claims that it is not valid json and contains no valud json head.
The output does use a valid json content header but that appears not to be enough for the script I am using.
So the question is, how can I convert the json output from a database call shown in first example, into the format the script is looking for show in the second example.
Code that creates json is fairly standard:
$stmt = $db3->prepare("SELECT week AS name, SUM(he.earnings) AS value FROM hotspot_earnings he INNER JOIN emrit_hotspots eh ON eh.hotspot_name = he.hotspot_name WHERE year = '2020' GROUP BY year, week");
$stmt->execute();
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
header('Content-type: application/json; charset=UTF-8');
echo json_encode($row, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
$stmt = $db3->prepare("SELECT week AS name, SUM(he.earnings) AS value FROM hotspot_earnings he INNER JOIN emrit_hotspots eh ON eh.hotspot_name = he.hotspot_name WHERE year = '2020' GROUP BY year, week");
$stmt->execute();
// Change here
$row = ['script' => $stmt->fetchAll(PDO::FETCH_ASSOC)];
Not sure if you can edit the initial json output with php. If it's called by AJAX and you can control the php file you can try something like this. Just build the new array.
$new_array = array('script' => $row);
echo json_encode($new_array, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
Related
I have never needed json previously, so I have almost zero experience...
I am outputting multiple arrays into a json file using the following code:
$file= 'myfile.json';
$contents = array('name' => $name,'busname' => $busname,'busdesc' => $busdesc, etc, etc);
$newcont=json_encode($contents, JSON_PRETTY_PRINT);
print_r($newcont);
file_put_contents($file, $newcont);
This is working as expected, and the output gives me something similar to this:
"name": [
"joe blogs",
"random name 2",
"random name 3",
etc,
etc
],
"busname": [
"ABC business",
"DEF business",
"HIJ business",
etc,
etc
],
"busdesc": [
"We do stuff",
"We do other stuff",
"We don't do anything",
etc,
etc
],
etc
Is it possible to (with a simple method) have the output to be more like:
"id1": [ "joe blogs", "ABC business", "We do stuff", etc ]
"id2": [ "random name 2", "DEF business", "We do other stuff", etc ]
"id3": [ "random name 3", "HIJ business", "We don't do anything", etc ]
etc
Layout is not particularly important, but getting them grouped together is.
I have had little success with getting relevant results from Google searches.
The reason I ask for a simple method, is that I am sure I can come up with some fancy loop that counts the number of entries first, then loops to keep adding the relevant data - and that may well be the answer, but I just wanted to know.
Many thanks
Edit:
I have undeleted this as my attempt at fixing did not work.
Here is the code:
$results = mysqli_query($con,"SELECT * FROM membersites WHERE id>0 ORDER BY id, busname");
$totalmem = mysqli_num_rows($results);
while($business = mysqli_fetch_array($results))
{
$r1 = $business['id'];
$id[]=$r1;
$r2 = $business['name'];
$name[]=$r2;
$r4 = $business['busname'];
$busname[]=$r4;
$r5 = $business['busdesc'];
$busdesc[]=$r5;
$all[] = "'id:''".$r1."''name:''".$r2."''busname:''".$r4."''busdesc:''".$r5."'";
}
$contents = array('members' => $all);
$newcont=json_encode($contents, JSON_PRETTY_PRINT);
print_r($newcont);
This almost worked as all the data is grouped correctly, however I am only getting one object (members) with all the users inside, not individual objects for each user.
Again, please bare in mind that this is the first project that I have had to output any json files.
Any help will be appreciated :)
Edit 2 (for clarity)
Final output needs to look like this
{
[
{
"id":"1",
"name":"joe blogs",
"busname":"ABC business",
"busdesc":"We do stuff"
},
{
"id":"2",
"name":"joe blogs",
"busname":"random name 2",
"busdesc":"We do other stuff"
},
etc
]
}
This file is going to be read by a mobile app - the app developer has just told me that it need to be in this format.
Apologies for being awkward.
When you loop on your records from DB, build a multi-dimensional array:
while($business = mysqli_fetch_array($results))
{
$all[] = [
'id' => $business['id'],
'name' => $business['name'],
'busname' => $business['busname'],
'busdesc' => $business['busdesc'],
];
// or
$all[] = $business;
// or
$all[ $business['id'] ] = $business;
}
Then you can encode your multidimensional array into JSON like this:
$newcont = json_encode($all, JSON_FORCE_OBJECT | JSON_PRETTY_PRINT);
the addition of JSON_FORCE_OBJECT will preserve numerical keys (i.e. when you add using $all[])
I'd recommend using PDO for database access instead of mysqli, which was originally developed as a stopgap replacement for the old mysql extension. But, using mysqli this should work:
$result = $con->query("SELECT id, name, busname, busdesc FROM membersites WHERE id > 0 ORDER BY id, busname");
$data = $result->fetch_all();
$json = json_encode($data, JSON_PRETTY_PRINT);
file_put_contents($file, $json);
You should avoid using SELECT * when possible. It reduces overhead, and ensures that you know the order of columns you're receiving. The mysqli_result::fetch_all() function pulls all the records at once, so no need for a loop.
I am querying 3 tables in PostgreSQL and converting the result into a nested json object. I am using PHP (and the Slim framework) as my application code. I am able to return a valid nested JSON object using PostgreSQL's built-in json operators. However, I'm having trouble rendering that JSON object in PHP.
PHP's json_encode operator seems to be trying to perform a JSON conversion on the provided obect (which is already in JSON format). And I can't get PHP to simply echo, print (or print_r) out the valid result provided by PostgreSQL. PHP keeps adding extra characters to the result.... I've tried :
(a) not using the PostgreSQL JSON operators,
(b) using PHP's json_decode before using json_encode,
(c) simply running echo and print_r statements, and
(d) I just started toying with using str_replace to remove the extraneous characters, but that is starting to feel scuzzy...
I'm pretty sure I'm doing something obviously wrong. I'm just at a standstill on this one. Any help is greatly appreciated!
The 3 tables are :
1. Company
2. Contact
3. Pic
CONTACT >----(:company_id)----- COMPANY ----(:company_id)-----< PIC
(A single company can have many contacts, and can have many pics... No relationship b/w the CONTACT and PIC tables)
HERE IS THE PHP CODE WHICH USES THE POSTGRESQL QUERY :
<?php
$app->get('/companies/{id}', function($request)
{
$db = pg_connect("host=localhost dbname=cool_db_name user=postgres")
or die('Could not connect: ' . pg_last_error());
$id = $request->getAttribute('id');
$query = "
SELECT row_to_json(t)
FROM (
SELECT company_id, company_name, company_street, company_city, company_state, company_zip, active_ind
, (
SELECT array_to_json(array_agg(row_to_json(c)))
FROM (
SELECT ct.contact_id, ct.contact_lname, ct.contact_fname, ct.contact_email, ct.active_ind
FROM contact ct
WHERE ct.company_id = c.company_id
ORDER by ct.contact_lname
) c
) AS contacts
, (
SELECT array_to_json(array_agg(row_to_json(p)))
FROM (
SELECT p.pic_id, p.pic_location, p.active_ind
FROM pic p
WHERE p.company_id = c.company_id
AND p.active_ind = 1
ORDER by p.pic_id
) p
) AS pics
FROM company c
WHERE c.alive_ind = 1 AND c.company_id = " . $id . "
) t
;";
$result = pg_query($db, $query);
while($row = pg_fetch_assoc($result))
{
$data[] = $row;
}
if(isset($data))
{
header('Content-Type: application/json');
echo json_encode($data);
}
});
1. Again, if I run that PostgreSQL query by itself, the result is VALID JSON (below) :
{
"company_id": 1,
"company_name": "Company #1",
"company_street": "111 Fun Ave",
"company_city": "Creve Coeur",
"company_state": "MO",
"company_zip": "10002",
"active_ind": 1,
"contacts": [{
"contact_id": 1,
"contact_lname": "Figgis",
"contact_fname": "Cyril",
"contact_email": "figgis#gmail.com",
"active_ind": 1
}, {
"contact_id": 2,
"contact_lname": "Kane",
"contact_fname": "Lana",
"contact_email": "lana#gmail.com",
"active_ind": 1
}, {
"contact_id": 3,
"contact_lname": "Tunt",
"contact_fname": "Cheryl",
"contact_email": "crazy#gmail.com",
"active_ind": 1
}],
"pics": [{
"pic_id": 1,
"pic_location": "profile/pic_900.jpg",
"active_ind": 1
}, {
"pic_id": 2,
"pic_location": "profile/pic_901.jpg",
"active_ind": 1
}, {
"pic_id": 3,
"pic_location": "profile/pic_902.jpg",
"active_ind": 1
}, {
"pic_id": 4,
"pic_location": "profile/pic_903.jpg",
"active_ind": 1
}]
}
(sorry for the poor formatting... it looks better in jsonlint.com)
2. ...but when I run that same query in the PHP application I get the following result (WEIRD JSON) :
[{"row_to_json":"{\"company_id\":1,\"company_name\":\"Company #1\",\"company_street\":\"111 Fun Ave\",\"company_city\":\"Creve Coeur\",\"company_state\":\"MO\",\"company_zip\":\"10002\",\"active_ind\":1,\"contacts\":[{\"contact_id\":1,\"contact_lname\":\"Figgis\",\"contact_fname\":\"Cyril\",\"contact_email\":\"figgis#gmail.com\",\"active_ind\":1},{\"contact_id\":2,\"contact_lname\":\"Kane\",\"contact_fname\":\"Lana\",\"contact_email\":\"lana#gmail.com\",\"active_ind\":1},{\"contact_id\":3,\"contact_lname\":\"Tunt\",\"contact_fname\":\"Cheryl\",\"contact_email\":\"crazy#gmail.com\",\"active_ind\":1}],\"pics\":[{\"pic_id\":1,\"pic_location\":\"profile/pic_900.jpg\",\"active_ind\":1},{\"pic_id\":2,\"pic_location\":\"profile/pic_901.jpg\",\"active_ind\":1},{\"pic_id\":3,\"pic_location\":\"profile/pic_902.jpg\",\"active_ind\":1},{\"pic_id\":4,\"pic_location\":\"profile/pic_903.jpg\",\"active_ind\":1}]}"}]
Like I said, I'm at a loss right now. Any help would be GREATLY appreciated. Thanks!
So, using that last escaped data format, you could do:
$noSlahes = str_replace("\", "", $yourEscapedJsonString);
This removes the slashes, replacing them with nothing. Now:
$jsonObject = json_decode($noSlahes);
Then, select rowToJson for it to be identical to your properly formatted JSON:
echo $jsonObject->row_to_json;
If someone else hits this problem and finds this question, both of the suggested answers are not an answer but a dirty workaround. The real problem lays on the query at the beginning and not on the php side.
Don't use ARRAY_AGG(ROW_TO_JSON())
Don't wrap any JSON function of PostgreSQL in ARRAY_AGG(), which will convert the JSON into a PostgreSQL Array and effectively will brake the JSON format escaping the quotes. A PosgreSQL array is not a JSON or a PHP array.
Use instead JSON_AGG()
The right aggregation function of JSON objects returned by any PostgreSQL JSON function like ROW_TO_JSON, JSON_BUILD_OBJECT etc, is done using JSON_AGG() function.
header('Content-Type: application/json');
$noSlashes = str_replace("\\","",$data); /* no need for json_encode() */
$hope = array_values($noSlashes[0]);
foreach($hope as $key => $value)
{
print $value;
}
I am trying to create a json object from my mysql database for a android project. I need an output something like this:
{
"feed": [
{
"id": 1,
"name": "National Geographic Channel",
"image": "http://api.androidhive.info/feed/img/cosmos.jpg",
"status": "\"Science is a beautiful and emotional human endeavor,\" says Brannon Braga, executive producer and director. \"And Cosmos is all about making science an experience.\"",
"profilePic": "http://api.androidhive.info/feed/img/nat.jpg",
"timeStamp": "1403375851930",
"url": null
},
{
"id": 2,
"name": "TIME",
"image": "http://api.androidhive.info/feed/img/time_best.jpg",
"status": "30 years of Cirque du Soleil's best photos",
"profilePic": "http://api.androidhive.info/feed/img/time.png",
"timeStamp": "1403375851930",
"url": "http://ti.me/1qW8MLB"
}
]
}
But I am getting ouput something like this:
{"feed":[{"id":"0","name":"punith","image":"","status":"ucfyfcyfffffffffffffffffffffffffffffffff","profilePic":"http:\/\/api.androidhive.info\/feed\/img\/nat.jpg","timestamp":"1403375851930","url":""}]}
Everything is on a single line and the id attribute should not be quotes. Is there anything I could do.This is my php file
<?php
define('HOST','');
define('USER','');
define('PASS','');
define('DB','');
$con = mysqli_connect(HOST,USER,PASS,DB);
$sql = "select * from timeline";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array('id'=>$row[0],
'name'=>$row[1],
'image'=>$row[2],
'status'=>$row[3],
'profilePic'=>$row[4],
'timestamp'=>$row[5],
'url'=>$row[6]
));
}
echo json_encode(array("feed"=>$result));
mysqli_close($con);
?>
And will it affect if the output is on a single line.
The database contains exactly the same columns used as attributes.
Thanks in advance
ID in quotes
ID is in quotes because it is a string, not an integer. You can change that by changing this:
array('id'=>$row[0]
to this:
array('id'=>intval($row[0])
"Pretty Printing"
Putting it on multiple lines will only affect readability but not how the data is computed - but you can prettify it: Pretty-Printing JSON with PHP
$output = json_encode(array("feed"=>$result), JSON_PRETTY_PRINT);
echo $output;
Try encoding with JSON_PRETTY_PRINT
$json_string = json_encode($data, JSON_PRETTY_PRINT);
where data is your result array.
in your case
echo json_encode(array("feed"=>$result),JSON_PRETTY_PRINT);
refer this Tutorial from the official PHP docs .
Aswell as the other answers, it would be more semantic to include the json header, I've found that just including this also helps with the appearance of the json itself so that it is formatted properly and not all one continuous string.
header('Content-Type: application/json');
For php>5.4
$json=json_encode(array("feed"=>$result),JSON_PRETTY_PRINT);
header('Content-Type: application/json');
print_r($json);
I have a ajax call calling a php file who runs a long php function which returns a JSON encoded array/object. Now I need to send HTML also into the ajax response. I thought about sending the HTML inside the array.
Is that a good practise?
Right now I cannot get it working, I get a NULL as value for that property. Don't know why.
$statHTML = '<table>';
foreach ($toHTML as $key=>$value) {
$statHTML.= '
<tr class="'.$key.'">
<td class="side">'.$value[0].'</td>
<td>'.$value[2].' '.$value[1].'</td>
</tr>';
}
$statHTML.= '</table>';
// echo $statHTML; // - this works
//function return
$answer = array('mostSearched'=>$mostSearched,
'timeOfDay' => $timeOfDay,
'mostSearchedDays'=>$mostSearchedDays,
'statHTML' => $statHTML
);
return json_encode($answer);
The ajax response from the console before the JSON.parse():
{
"mostSearched": {
"title": "Most serached houses",
"colNames": [21],
"rowNames": [2013],
"rows": [1]
},
"timeOfDay": {
"title": "Time of search",
"colNames": ["07:30"],
"rowNames": ["07:30"],
"rows": [
[1]
]
},
"mostSearchedDays": {
"title": "Most searched days",
"colNames": ["2013-12-21", "2013-12-22", "2013-12-23", "2013-12-24", "2013-12-25", "2013-12-26", "2013-12-27"],
"rowNames": ["2013-12-21", "2013-12-22", "2013-12-23", "2013-12-24", "2013-12-25", "2013-12-26", "2013-12-27"],
"rows": [
[1, 1, 1, 1, 1, 1, 1]
]
},
"statHTML": null
}
From php.net:
Parameters
value
The value being encoded. Can be any type except a resource.
All string data must be UTF-8 encoded.
So use:
$answer = array('mostSearched'=>$mostSearched,
'timeOfDay' => $timeOfDay,
'mostSearchedDays'=>$mostSearchedDays,
'statHTML' => utf8_encode($statHTML)
);
return json_encode($answer);
Most likely the build-in JSON parser used by PHP cannot properly parse the HTML, the easiest way to solve the issue is to base64 encode the html on the server, and then decode it on the client, using either the newer atob and btoa base64 methods, or one of the many polyfills out there.
use base64_enccode in this at the time of conversion
$answer = array('statHTML'=>base64_encode('<h1>html in here</h1>'));
echo json_encode($answer);exit;
And at the time of getting response from ajax
atob(response.statHTML);
Hope you understand how it works
So this is where to view my json file: http://alyssayango.x10.mx/
this is my php file for that:
<?php
include('connectdb.php');
$sql = "SELECT * FROM tblmovies ORDER BY _id";
$result = mysql_query($sql);
if($result === FALSE) {
die(mysql_error()); // TODO: better error handling
}
$set = array();
while($row1 = mysql_fetch_assoc($result)) {
$set[] = $row1;
}
echo json_encode($set);
and the output is:
[{"_id":"3","movie_name":"Despicable Me 2","movie_cinema_number":"CINEMA 1","movie_length":"1hr. 40mins.","movie_type":"GP","movie_schedules":"12:10 PM | 02:25 PM | 04:40 PM","movie_image_url":"http:\/\/i39.tinypic.com\/szizo4.jpg"},{"_id":"4","movie_name":"White House Down","movie_cinema_number":"CINEMA 2","movie_length":"2 hrs. 10 mins.","movie_type":"PG-13","movie_schedules":"12:30 PM | 03:20 PM | 06:10 PM","movie_image_url":"http:\/\/i39.tinypic.com\/vp9n9j.jpg"},{"_id":"5","movie_name":"My Lady Boss","movie_cinema_number":"CINEMA 3","movie_length":"1hr. 50 mins.","movie_type":"PG-13","movie_schedules":"01:00 PM | 03:30 PM | 06:00 PM","movie_image_url":"http:\/\/i44.tinypic.com\/2qlv08z.jpg"},{"_id":"6","movie_name":"Four Sisters And A Wedding","movie_cinema_number":"CINEMA 4","movie_length":"2 hrs. 5 mins. ","movie_type":"PG-13","movie_schedules":"12:30 PM | 03:10 PM | 05:50 PM","movie_image_url":"http:\/\/i44.tinypic.com\/9iv0d1.jpg"}]
what seems to be wrong that I do in here? URL is displayed as: http:\ /\ /i44.tinypic.com\ /9iv0d1.jpg where it should be http://i44.tinypic.com/9iv0d1.jpg
The JSON format is often used for serializing and transmitting structured data over a network connection. It is used primarily to transmit data between a server and web application, serving as an alternative to XML.
If you create an API that should be:
$array = array("title" => "TEST", "username" => "test"); // Creating a array
echo json_encode($array); // Printing json
Client want to request and get response:
$json = file_get_contents('http://www.example.com/test/films.json'); // Your url
$array = json_decode($json); // Your first array its here!
More: http://en.wikipedia.org/wiki/JSON
Warning: You can't edit or tidy your json response! It is good!
The problem does not exists, actually.
What you're doing wrong is that you're using a piece of your JSON string without decoding it beforehand. Just use json_decode(..) if you're within PHP or the equivalent javascript function to decode JSON.
Once you did that, you'll have an object / an array which contains the data in the correct form.