PHP JSON Data Formatting - php

I'm writing an application that takes dates and runs an SQL query and spits out JSON data. So far everything seems to be working except that using json_encode it doesn't seem that my json data is correctly formatted as I get a validation error on Json lint. The issue that I see is that after echo ","; puts a comma where it needs to after my objects it then puts one after the last which throws another error. Some how I only need it up until the last dataset...
echo "[";
// Loop through the records returned.
while($row = $query->fetch(PDO::FETCH_ASSOC)) {
echo json_encode($row), "\n\n";
$date = $row['date'];
$count = $row['count'];
echo ",";
}
echo "]";
And this is my Json data
[
{
"Date": "2015-01-01",
"Count": "150"
},
{
"Date": "2015-01-02",
"Count": "262"
},
{
"Date": "2015-01-03",
"Count": "163"
},
]

while ($row = $query->fetch(PDO::FETCH_ASSOC))
$data_arr[] = [$row['date'], $row['count']];
echo json_encode($data_arr);

Related

How to get data in json form

Currently, I am making an API and I want the data in JSON format. But I am not able to get it. It is coming in normal form. But how to convert it into JSON. If I am writing json_encode($response) outside the loop then I am getting the data in json format but only one data.
If i wriing the json encode inside the loop then i am getting all the data but not in JSON form. How to solve this. I am not able to get the perfect solution for ths question.
$tsym = strtolower($_REQUEST['tsym']);
$time = strtolower($_REQUEST['time']);
$mil = $time;
$seconds = $mil / 1000;
$normal_date = date("Y-m-d H:i:s", $seconds);
$sql = "SELECT * FROM `forex` where pair='".$tsym."' and date >= '".$normal_date."' order by date limit 0,10";
$result = mysqli_query($conn, $sql);
$response = array();
while($rows = mysqli_fetch_assoc($result)){
$from_sym = $rows['pair'];
//if(!isset($response[$from_sym]))
{
$response[$from_sym] = $rows;
//echo json_encode($response, true);
//}
print_r( json_encode($response)); //this prints all the data but not
in json form
}
print_r( json_encode($response)); //this prints single data but in
json form
I want all the data but in json form. how to get it? Thank you for the help.
I want data like this:
{
"CHFJPY": {
"id": "33",
"pair": "CHFJPY",
"date": "2018-04-22 20:42:21",
"price": "110.413",
"change_rate": "0",
"fetched": "1"
}
},
{
"CHFJPY": {
"id": "75",
"pair": "CHFJPY",
"date": "2018-04-22 20:42:29",
"price": "110.413",
"change_rate": "0",
"fetched": "1"
}
},
{
"CHFJPY": {
"id": "117",
"pair": "CHFJPY",
"date": "2018-04-23 11:25:47",
"price": "110.585",
"change_rate": "0",
"fetched": "1"
}
},
{
"CHFJPY": {
"id": "159",
"pair": "CHFJPY",
"date": "2018-04-23 12:34:54",
"price": "110.816",
"change_rate": "0",
"fetched": "1"
}
},
{
"CHFJPY": {
"id": "201",
"pair": "CHFJPY",
"date": "2018-04-23 12:35:04",
"price": "110.825",
"change_rate": "0",
"fetched": "1"
}
}
But i am getting only one data.
You have to append your row to the final array $response in your while loop
$response = array();
while($rows = mysqli_fetch_assoc($result)){
$from_sym = $rows['pair'];
$res[$from_sym] = $rows;
$response[] = $res;
}
print_r(json_encode($response));
You need to move the json_encode into the outside of while loop
<?php
$tsym_escaped = mysqli_real_escape_string($conn, $_REQUEST['tsym']);
$date = date("Y-m-d H:i:s", $_REQUEST['time']/1000);
$sql = sprintf(
"SELECT * FROM `forex` WHERE `pain`='%s' AND `date`>='%s' ORDER BY `date` LIMIT 0,10",
$tsym_escaped,
$date
);
$result = mysqli_query($conn, $sql);
$response = array();
while($row = mysqli_fetch_assoc($result)){
$response[$row['pair']] = $row;
}
echo json_encode($response);
Also, the way you're passing the data into the SQL query is insecure and can lead into a SQL injection.
is not clear why you have not json so .. in more clear way try
while($rows = mysqli_fetch_assoc($result)){
$response[$rows['pair']] = $rows;
}
$myJSON = json_encode($response);
var_dump($myJSON);
this should buil a $reponse array with the related vleus for each 'pair' index
but could be you need all the rows result so try
while($rows = mysqli_fetch_assoc($result)){
$response[] = $rows;
}
$mySecondJSON = json_encode($response);
var_dump($mySecondJSON);
or
while($rows = mysqli_fetch_assoc($result)){
$response[] = $rows['pair'];
}
$myOtherJSON = json_encode($response);
var_dump($myOtherJSON);

How to parse json array using php foreach?

I want to get id,url,img and title of videos in the JSON data.My current code doesn't output anything
could any one tell me what i am doing wrong.Thanks
$code2 = stripslashes($_POST['outputtext']);
$data = json_decode($code2, true);
$i = 0;
foreach($data->videos as $values)
{
echo $values->id . "\n";
echo $values->url . "\n";
echo $values->img . "\n";
echo $values->title . "\n";
$i++;
}
data:
{
"cat": {
"id": "1234567",
"source_id": null,
"title_en": "first season",
"description_en": "This is spring category ",
},
"videos": [{
"id": "312412343",
"url": "\/2015-07-17\/1abcd.mp4",
"img": "image\/44\/\/2015-07-17\/1abcd.jpg",
"title": "first",
}, {
"id": "2342343",
"url": "\/2015-07-16\/2dcdeg.mp4",
"img": "images\/44\/\/2015-07-16\/2dcdeg.jpg",
"title": "second",
}];
}
validated json data:
{
"cat":{
"id":"1234567",
"source_id":null,
"title_en":"first season",
"description_en":"This is spring category "
},
"videos":[
{
"id":"312412343",
"url":"\/2015-07-17\/1abcd.mp4",
"img":"image\/44\/\/2015-07-17\/1abcd.jpg",
"title":"first"
},
{
"id":"2342343",
"url":"\/2015-07-16\/2dcdeg.mp4",
"img":"images\/44\/\/2015-07-16\/2dcdeg.jpg",
"title":"second"
}
]
}
Because you call
$data = json_decode($code2, true);
your $data is an array and not an object as you try to access it. So either access it as regular array, or change 2nd argument of json_decode() to false (or removeit as this is default), as this is what controls conversion behavior.
See docs: http://php.net/manual/en/function.json-decode.php
Your data is not a valid JSON (; at the end, redundant and missing comas - it's simply broken).
In case of such problems, var_dump() is pretty helpful to inspect what data you are really working with.

PHP/MYSQL/JSON: Simplify JSON for API

Hi I am trying to create an API that converts a results array from a database call into json that can be easily parsed.
Using the simple command json_encode, my JSON is a complicated, verbose mess of nested objects and arrays that is proving hard to parse on the other end.
Can anyone suggest a way to pare this down to the key information that should be provided: userid, long comment (lcom) and short comment (shcom) and how to send this as an API?
Thanks in advance for any suggestions
Here is the current JSON output produced from the following query and code:
$sql = "SELECT userid,shcom,lcom FROM comments WHERE userid = 1 LIMIT 4";
$res = mysql_query($sql) or die(mysql_error());
$comments = array();
while($row = mysql_fetch_array($res)) {
$comments[] = array('row'=>$row);
}
echo json_encode(array('comments'=>$comments));
Json output:
{
"comments": [
{
"row": {
"0": "1",
"userid": "1",
"1": "hello",
"shcom": "hello",
"2": "hellothere",
"lcom”: "hellothere"
}
},
{
"row": {
"0": "1",
"userid": "1",
“1”: ”agreed”,
"shcom”: ”agreed”,
“2”: ”agreedforonce”,
"lcom”: ”agreedforonce”
}
},
{
"row": {
"0": "1",
"userid": "1",
"1": "gohome",
"shcom”: ”gohome“,
“2”: ”gohomenow”,
"lcom: ”gohomenow”
}
},
{
"row": {
"0": "1",
"userid": "1",
"1": "getout”,
"shcom”: ”getout”,
“2”: ”getoutofhere”,
"lcom: ”getoutofhere”
}
}
]
}
You should be using mysqli rather than mysql since mysql is deprecated. Regardless, the problems in your code are happening because of two reasons. One, mysql_fetch_array does not produce the results you are expecting. Two, in your iteration you are not extracting the answers the right way. To resolve, use mysq_fetch_assoc and push only each $row to your final array.
Replace this:
while($row = mysql_fetch_array($res)) {
$comments[] = array('row'=>$row);
}
to this:
while($row = mysql_fetch_assoc($res)) {
$comments[] = $row;
}

Json_Encode php last comma

For a school project I have to display database data as a valid json file.
$result = mysqli_query($mysqli, "SELECT * FROM `csvdata`");
echo "{ \"films\" : [";
while ($row = mysqli_fetch_array($result)) {
$jsonResult = json_encode($row);
echo $jsonResult;
echo ",";
}
echo "]}";
The output i get is:
{
"films": [
{
"0": "Man on fire",
"titel": "Man on fire",
"1": "Actie",
"genre": "Actie"
},
{
"0": "Dumb and Dumberer",
"titel": "Dumb and Dumberer",
"1": "Comedy",
"genre": "Comedy"
},
{
"0": "DefQon 2014",
"titel": "DefQon 2014",
"1": "Muziek",
"genre": "Muziek"
},
]
}
Now my question is, how do I remove the last comma, I cannot find that. And all data tells the data 2 times, I also don't know how to avoid this.
Let json_encode handle the entire thing - build one array of data, and use json_encode on that.
$result = mysqli_query($mysqli, "SELECT * FROM `csvdata`");
$response = array();
$response['films'] = array();
while ($row = mysqli_fetch_array($result)) {
$response['films'][] = $row;
}
echo json_encode($response);
A good way to do this, is to not place a comma after writing every record, but instead before every record.
Then all you have to do, is add an if statement that doesn't output the comma for the very first row.

Json Parsing error using JSON.parse()

I have developed an api which will post some data in json format to be used in an android app. However I am getting json parsing error. I am new to this whole json thing so unable to understand what the error means.
This is my json encoded output that the php backend generates
{
"data": [
{
"id": "2",
"name": "Rice",
"price": "120",
"description": "Plain Rice",
"image": "6990_abstract-photo-2.jpg",
"time": "12 mins",
"catagory": "Lunch",
"subcat": ""
}
]
}{
"data": [
{
"id": "4",
"name": "Dal",
"price": "5",
"description": "dadadad",
"image": "",
"time": "20 mins",
"catagory": "Dinner",
"subcat": ""
}
]
}{
"data": [
"catagory": "Soup"
]
}
This is the error the online json parser gives
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 2 column 1 of the JSON data
What is actually wrong here? Could you please provide me with the correct json output for the following data?
This should clear it up
$main = array();
while($row = $result->fetch(PDO::FETCH_ASSOC)){
$cat = $row['category'];
$query1 = "SELECT * FROM item WHERE catagory='$cat'"; //Prepare login query
$value = $DBH->query($query1);
if($row1 = $value->fetch(PDO::FETCH_OBJ))
{
$main[] = array('data'=>array($row1));
}
else
{
$main[] = array('data'=>array('catagory'=>$row['category']));
}
}
echo json_encode($main);
You shouldn't create your json string by hand. Create your array structure, then finally invoke json_encode() at the end.
$data = array();
try
{
$query = "SELECT category FROM category"; // select category FROM category? what?
$result= $DBH->query($query);
while($row = $result->fetch(PDO::FETCH_ASSOC)){
$cat = $row['category'];
$query1 = "SELECT * FROM item WHERE catagory='$cat'";
$value = $DBH->query($query1);
if($value->rowCount() > 0) {
$data[] = array('data' => $value->fetch(PDO::FETCH_ASSOC));
}
else {
$sub = array('category' => $row['category']);
$data[] = array('data' => $sub);
}
}
$result->closeCursor();
$DBH = null;
echo json_encode($data); // encode at the end
}
catch(PDOException $e)
{
print $e->getMessage ();
die();
}

Categories