My JSON response seems to have excess keys in it. Any idea why?
Here is an excerpt from the JSON response:
{
"0": "1",
"id": "1",
"1": "XX University",
"name": "XX University",
"2": "http:\/\/ree.com\/images\/xxUniversity.png",
"backgroundImageUrl": "http:\/\/ree.com\/images\/XXUniversityLogo.png",
"3": "http:\/\/ree.com\/images\/xxUniversity.png",
"logoImageUrl": "http:\/\/ree.com\/images\/XXUniversityLogo.png"
},
Here is my PHP code:
$query = "SELECT * from $entity"; //Bad security,for a different question
$results = mysqli_query($con,$query);
//Parse to JSON
$json=array();
while($row=mysqli_fetch_array($results)){
$json[]=$row;
}
//Close connection
mysqli_close($con);
//Encode and send response as JSON (using the entity type as a parameter)
//echo json_encode(array($entity => $json), JSON_FORCE_OBJECT);
echo json_encode(array ($entity =>$json));
Your problem is mysqli_fetch_array. You want to pass MYSQLI_ASSOC as a second parameter.
while($row=mysqli_fetch_array($results,MYSQLI_ASSOC)){
$json[]=$row;
}
From the docs:
This optional parameter is a constant indicating what type of array should be produced from the current row data. The possible values for this parameter are the constants MYSQLI_ASSOC, MYSQLI_NUM, or MYSQLI_BOTH.
By using the MYSQLI_ASSOC constant this function will behave identically to the mysqli_fetch_assoc(), while MYSQLI_NUM will behave identically to the mysqli_fetch_row() function. The final option MYSQLI_BOTH will create a single array with the attributes of both.
mysqli_fetch_array per default retrieves both numeric and named index.
You have to specify an additional parameters to get only the desired ones.
MYSQLI_ASSOC retrieves the named array,
MYSQLI_NUM retrieves just the integer indexed one
MYSQLI_BOTH retrieves both :)
Related
I have below json data and decode it to display on the screen. When I check the type of the value, it shows array instead of object. How to get actual type of value in PHP.
JSON is
{ "allData" : { "image" : [], "contents": {.., "box": {}, "text":[]} } }
When I decode and parse the above JSON data the "allData", "contents", "box" type are shows as array instead of object. How can I get those type as object and "image" type as array. Please help.
Thanks,
Guru
This normally occurs when you are using the true option in the json_decode function.
For eg.,
$str = '{"allData":{"image":["img1.png"],"contents":{"title":"title name","box":{"name":["sample text 1","sample text2"]},"text":[]}}}';
var_dump(json_decode($str, true));
Just try to remove the true in the json_decode function and you should get an object.
Hope this helps.
If you use json_decode with the true option, it will return the result as an array.
Maybe you can check this link.
If you get "Cannot use object of type stdClass as array" the error, you can look at this answer.
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
?>
Extract from the RFC 7159 (JSON) :
These are the six structural characters:
begin-array = ws %x5B ws ; [ left square bracket
begin-object = ws %x7B ws ; { left curly bracket
end-array = ws %x5D ws ; ] right square bracket
end-object = ws %x7D ws ; } right curly bracket
..
However: php allows you to treat the result as an array (of arrays)
so:
json_decode($json, true); // return as array
returns the result as an array.
and
json_decode($json)
gives you the result as Objects AND arrays . So given your example:
"allData" : { "image" : [], ..
returns a stdClass-Object with the field "image" of type array. The array is empty for your example.
So to retrieve all images, use something like:
$result=json_decode($json);
foreach($result->allData->image as $img) {
echo "found image: $img.";
}
this question comes from the posting I found here:
DataTables Multiple Tables from Multiple JSON Arrays
I'd like to know the simplest and best way to generate the JSON below. I can see the pattern is 'JSON object -> Array Header -> Array -> JSON object' but I do not know how to do this in PHP, from a mySQLi query result. I imagine having a mySQL table with a 'policies' and 'services' column so the query might look something like:
Select name, id, score, type from myTable where type = 'policies' and
type = 'services'
And the result would come back something like:
name id score type
A 1 0 policies
B 2 0 services
But then how would I take that query and generate this JSON in php?
{
"Policies": [
{
"name": "A",
"id": "1",
"score": "0"
}
],
"Services": [
{
"name": "B",
"id": "2",
"score": "0"
}
]
}
Thanks for your help!
Start by creating the new empty array.
Then, iterate through the result and add it in the correct sub-array:
$new = [];
foreach ($result as $item) {
// Uppercase the first character
$type = ucfirst($item['type']);
if (!isset($new[$type])) {
// This type doesn't exist in the new array yet, let's create it.
$new[$type] = [];
}
// Add the item
$new[$type][] = $item;
}
// Output it as json
echo json_encode($new, JSON_PRETTY_PRINT);
The above code will also work if new types are added to the database.
PS. The JSON_PRETTY_PRINT argument is just to make the json string a bit more readable while developing. When everything looks good, you can remove it.
I have an array like so
id | userID | item
1 ! 1 | {"property": 0, "property": "string"}
2 ! 1 | {"property": 4, "property": "string2"}
and I wish to return one array with like so:
[{
"property": 0,
"property": "string"
},
{
"property": 4,
"property": "string2"
}]
No matter what I try I cannot seem to get it to work properly. Either I get a whole string so number values get converted, or I get an object with \" everywhere. Currently I have this code
if ($query = $mysqli->query("SELECT item FROM userItems WHERE userID = 'id' "))
{
while ($row = $query->fetch_object())
{
$result->items[count($result)] = $row;
}
}
$test = stripslashes(json_encode($result->items));
which returns this ...
{"1":{"item":"{"property":"0","property":"string"}"}}
Been trying to solve it for hours and can't get it right
I tried your code and there're two main things:
you're building an array of associative arrays but associative array tends to overwrite identical associative keys with the latter in your code - in your case both keys are property,
the data you're retrieving from DB (userItems.item) already seems to be JSON encoded so you need to call json_decode() somewhere instead of calling json_encode() again; decoding your $row->item ($result->items[count($result)] = json_decode($row->item);) seems to do the trick.
Just as a sidenote you should consider wrapping your id parameter in SQL query into mysqli_real_escape_string() or so.
Let me know if that helped and you see the desired result now.
I am trying to create a simple android application that takes data from a database and displays it in a list format on the android screen. I made a php script that queries the database and returns a json object. I convert the json object into json array and extract the relevant data for display. But I am getting this error "JSONException: type org.json.JSONObject cannot be converted to JSONArray".
Following is my php script -
// response Array
$response = array("tag" => $tag, "success" => 0, "error" => 0);
$username = $_POST['username'];
$events = $db->viewAttendingEvent($username);
if ($events) {
$response["success"] = 1;
$response["event"]["owner"] = $events["owner"];
$response["event"]["friendsnames"] = $events["friendsnames"];
$response["event"]["vote"] = $events["vote"];
$response["event"]["accepted"] = $events["accepted"];
$response["event"]["eventname"] = $events["eventname"];
$response["event"]["eventnumber"] = $events["eventnumber"];
$response["event"]["created_at"] = $events["created_at"];
echo json_encode($response);
This is the json which I receive back :
{
"tag": "view_invitations",
"success": 1,
"error": 0,
"event": {
"owner": "jkkkkoopp",
"friendsnames": "don",
"vote": "0",
"accepted": "f",
"eventname": "yyy",
"eventnumber": "11",
"created_at": "2014-05-29 22:27:31.843528"
}
}
I am trying to extract 'event' from this json object, which is not an array.
it should be
{
"event": [
{
"owner": "jkkkkoopp",
"friendsnames": "don",
"vote": "0",
"accepted": "f",
"eventname": "yyy",
"eventnumber": "11",
"created_at": "2014-05-2922: 27: 31.843528"
}
]
}
Can someone help me how to make this a valid jsonArray ? Thanks
If you're looking to get a JavaScript 'Array' (from which I mean an Object with nothing but integer keys) then you need to only have integer keys in your PHP Array.
This article is a pretty good resource and explains some of the differences between arrays and objects in javascript. The relevant quote here comes from the What Arrays Are section (emphasis mine):
Javascript arrays are a type of object used for storing multiple
values in a single variable. Each value gets numeric index and may be
any data type.
No it should not be what you proposed it should be. If that were the case you would have to have your php be this:
$response["event"][0]["owner"] = $events["owner"];
$response["event"][0]["friendsnames"] = $events["friendsnames"];
$response["event"][0]["vote"] = $events["vote"];
$response["event"][0]["accepted"] = $events["accepted"];
$response["event"][0]["eventname"] = $events["eventname"];
$response["event"][0]["eventnumber"] = $events["eventnumber"];
$response["event"][0]["created_at"] = $events["created_at"];
The way you have it now is event is an associative array so it converts it to an object. You are expecting that event = an array of objects. So you need to either change your php code to make event be an array of objects (as demonstrated above) or you need to modify your expectations to have event = an object.
I have the following PHP code:
$data=mysql_query("SELECT * FROM notes WHERE rootNoteId='$noteId'");
$mainArray;
while($result = mysql_fetch_array($data))
{
$mainArray[]=$result;
}
$sendback = array(
"mainArray" => $mainArray
);
sendResponse(200, json_encode($sendback));
My table 'notes' has the following fields:
'noteId'
'authorName'
'noteBody'
However my return JSON string has the following format:
{
"0": "3",
"1": "Moe Bit",
"2": "Sub sub ",
"noteId": "3",
"authorName": "Moe Bit",
"noteBody": "Sub sub "
}
Why is it adding 0,1,2 indexes for the array with duplicate values of my table fields? I just want noteId, authorName, and noteBody-I'm not sure where it's coming up with "0","1","2".
mysql_fetch_array() in it's default "mode" fetches the result as associative & numeric array. So you get field names (what you want) and numeric indexes (the numbers you don't want).
To solve this pass the constant "MYSQL_ASSOC" as the second parameter to "mysql_fetch_array" or use the mysql_fetch_assoc() function.
try either mysql_fetch_assoc or mysql_fetch_object