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();
}
Related
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);
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);
I am using slimphp v2 and I have the following function
function gt($user) {
$sql = "select id, id as categoryId, mobile, task from actions where status=0";
try {
$db = newDB($user);
$stmt = $db - > prepare($sql);
$stmt - > execute();
$gs = $stmt - > fetchAll(PDO::FETCH_OBJ);
if ($gs) {
$db = null;
echo json_encode($gs, JSON_UNESCAPED_UNICODE);
} else {
echo "Not Found";
}
} catch (PDOException $e) {
echo '{"error":{"text":'.$e - > getMessage().
'}}';
}
}
The default json output looks like:
[{
"id": "1",
"categoryId": "1",
"mobile": "111",
"task": "test"
},
{
"id": "2",
"categoryId": "2",
"mobile": "222",
"task": "test2"
}]
and the output that i am trying to make. I need to generate an ID: 1_(id) then format it like this
[{
id: "1",
task: "test",
}, {
ID: "1_1", //generate this, add 1_id
categoryId: "1",
mobile: "00000",
}, {
id: "2",
task: "test2",
}, {
ID: "1_2", //generate this, add 1_id
categoryId: "2",
mobile: "11111"
}];
Is it possible?
Thanks
I'm not sure if this is exactly what your after but you can gain the desired JSON output by converting your original JSON into an associative array and then restructure the data on each iteration using a Foreach() loop into a new assoc array. After that, you can just convert it back to JSON using json_encode().
Code:
$json = '[{
"id": "1",
"categoryId": "1",
"mobile": "111",
"task": "test"
},
{
"id": "2",
"categoryId": "2",
"mobile": "222",
"task": "test2"
}]';
$jsonArr = json_decode($json, TRUE);
$newArr = [];
foreach ($jsonArr as $v) {
$newArr[] = ['id:'=>$v['id'], 'task:' => $v['task']];
$newArr[] = ['ID:'=>'1_' . $v['id'], 'categoryId' => $v['categoryId'], 'mobile'=>$v['mobile']];
}
$newJson = json_encode($newArr);
var_dump($newJson);
Output:
[{
"id:": "1",
"task:": "test"
}, {
"ID:": "1_1",
"categoryId": "1",
"mobile": "111"
}, {
"id:": "2",
"task:": "test2"
}, {
"ID:": "1_2",
"categoryId": "2",
"mobile": "222"
}]
Edit -- Updated Answer
As discussed in comments, your outputting your SQL array as an object. I've set the Fetch to output as an associative array using PDO::FETCH_ASSOC and changed the foreach() loop to reference the assoc array $gs. This should work but if not then output your results for $gs again using var_dump($gs). You will still need to encode to JSON if needed but this line has been commented out.
function gt($user) {
$sql = "select id, id as categoryId, mobile, task from actions where status=0";
try {
$db = newDB($user);
$stmt = $db->prepare($sql);
$stmt->execute();
$gs = $stmt->fetchAll(PDO::FETCH_ASSOC); //Fetch as Associative Array
if ($gs) {
$db = null;
$newArr = [];
foreach ($gs as $v) { //$gs Array should still work with foreach loop
$newArr[] = ['id:'=>$v['id'], 'task:' => $v['task']];
$newArr[] = ['ID:'=>'1_' . $v['id'], 'categoryId' => $v['categoryId'], 'mobile'=>$v['mobile']];
}
//$newJson = json_encode($newArr); //JSON encode here if you want it converted to JSON.
} else {
echo "Not Found";
}
} catch(PDOException $e) {
//error_log($e->getMessage(), 3, '/var/tmp/php.log');
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
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();
}
$result = $db->query($select_msgsum); //query the new msgsum table
//defining label that google needs
$col1 = array();
$col1["id"]="";
$col1["label"]="MessageType";
$Col1["pattern"]="";
$col1["type"]="string";
$col2 = array();
$col2["id"]="";
$col2["label"]="MessageCount";
$Col2["pattern"]="";
$col2["type"]="number";
// rows?
//filling the json data to it
while($data=$result->fetchArray()){
array_push($col1, $data['msg_type']);
array_push($col2, $data['msg_count']);
}
$cols = array($col1, $col2);
file_put_contents('../json/chart_data.json', json_encode($cols));
?>
The result i get is as following which is not accepted as explained here: https://developers.google.com/chart/interactive/docs/php_example
[
{
"0": "General question",
"1": "Job-fulltime",
"2": "Job-parttime",
"3": "Just Hello",
"id": "",
"label": "MessageType",
"type": "string"
},
{
"0": 6,
"1": 3,
"2": 9,
"3": 12,
"id": "",
"label": "MessageCount",
"type": "number"
}
]
you can directly convert the result from query to JSON.. try this ..
$result = $db->query($select_msgsum);
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
print json_encode($rows);