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.
Related
I'm new to php and am trying to encode 2 arrays together into one JSON object.
Currently this is the JSON output:
{
"image_link": "some url",
"zoomin_level": "8",
"zoomout_level": "18.5",
"position_lat": "32.913105",
"position_long": "-117.140363",
}
What I like to achieve is the following:
{
"image_link": "some url",
"zoomin_level": "2",
"zoomout_level": "15",
"position_lat": "32.9212",
"position_long": "-117.124",
"locations": {
"1": {
"image_link": "some url",
"name": "Name",
"lat": 32.222,
"marker_long": -112.222
},
"2": {
"image_link": "some url",
"name": "Name",
"lat": 32.222,
"marker_long": -112.222
}
}
}
This is similar to the question asked here: PHP json_encode multiple arrays into one object
However mine is a bit different because I like to add the 2nd array as part of a key-value part within the 1st array.
Here's my php code:
$sql = "select * from first_table";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
$rowCount = $result->num_rows;
$index = 1 ;
$newArray = [];
while($row =mysqli_fetch_assoc($result))
{
$sqlnew = "select * from second_table";
$resultnew = mysqli_query($connection, $sqlnew) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$jsonData = array();
$rowCountnew = $resultnew->num_rows;
$indexnew = 1;
if ($rowCountnew >0)
{
while($rownew =mysqli_fetch_assoc($resultnew))
{
$locations[$indexnew] = array("image_link" => $rownew['image_link'], "name" => $rownew['name'], "position_lat" => doubleval($rownew['position_lat']), "position_long" => doubleval($rownew['position_long']) );
++$indexnew;
}
}
$newArray[$row['map_type']] = $row['map_value'];
}
echo json_encode($newArray);
Not knowing the proper syntax, I tried to perform the following which resulted in garbage: echo json_encode($newArray, "locations" =>$locations);
Try:
$newArray['locations'] = $locations;
echo json_encode ($newArray);
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;
}
So i want to generate my JSON for a angular app in this format. The result will be used for a dropdown and i need it to be in this particular format
[
{
id:1,
post_title:title1},
{
id:2,
post_title:title1},
{
id:3,
post_title:title3},
and so on ...
]
But when i send my JSON back to my angular app it looks like this
{
"0": {
"id": "1",
"post_title": "Batman Ipsum"
},
"1": {
"id": "2",
"post_title": "Title fit for a (precariously enthroned) king"
},
"2": {
"id": "3",
"post_title": "Cupcake Ipsum"
},
"3": {
"id": "4",
"post_title": "The most presidential lorem ipsum in history."
},
"4": {
"id": "5",
"post_title": "Quote Ipsum"
},
"5": {
"id": "6",
"post_title": "Yet another Batman Ipsum"
},
"6": {
"id": "9",
"post_title": "Yet another Harry Potter ipsum"
},
"7": {
"id": "10",
"post_title": "Vegetable Ipsum"
}
}
How to change it to the format that i want?
My php code
function fetchPagesNames()
{
$response = array();
$resultArray=array();
try {
$sql = "SELECT id,post_title FROM posts";
$result = mysql_query($sql) or trigger_error(mysql_error() . $sql);
$resultCount = mysql_num_rows($result);
if ($resultCount > 0) {
while ($row = mysql_fetch_assoc($result)) {
$resultArray[]=$row;
}
$response['status'] = 'Success';
$response['message'] = "Post's Obtained";
$response['results'] = $resultArray;
} else {
$response['status'] = 'Error';
$response['message'] = 'No Pages in the Database';
die();
}
echo json_encode($response,JSON_FORCE_OBJECT);
} catch (exception $e) {
$response['status'] = 'Error';
$response['message'] = $e->getMessage();
echo json_encode($response);
die();
}
}
What changes are needed?
There are two major differences between your "required" format and the output you're getting:
The format you've quoted as being required is not actually valid JSON because you're missing the quotes.
The JSON format is very explicit in that it must have quotes around property names and string values. The JSON you're getting outputted is correct in this regard.
Your required output has an outer layer that is an array, whereas your actual output has an object, with numbered elements as strings.
The reason for this is because you're using JSON_FORCE_OBJECT in your call to json_encode(). This argument forces all parts of the JSON otput to be processed as objects not arrays. Remove this and you'll get the top-level array that you're looking for.
Remove JSON_FORCE_OBJECT from json_encode().
Use json_encode for print object.
or look like this...
try {
$sql = "SELECT * FROM tekst";
$result = $dao->conn->query($sql);
//$resultCount = mysql_num_rows($result);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$resultArray[] = $row;
}
echo json_encode(
$resultArray
);
} else {
$response['status'] = 'Error';
$response['message'] = 'No Pages in the Database';
die();
}
} catch (exception $e) {
$response['status'] = 'Error';
$response['message'] = $e->getMessage();
echo json_encode($response);
die();
}
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);
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();
}