Can/Should JSON format be condensed? - php

A sql query returns many rows of the following simple structure:
"name", id
I need to provide it in JSON format. I assume the proper format is an array of the simple structures as seen below. Although I'm not sure if there is a less verbose structure that would be preferable. for example, should I avoid the repeating name/id field names somehow to reduce size?
[
{
"name": "greg",
"id": 13
},
{
"name": "greg",
"id": 12
},
{
"name": "greg",
"id": 11
}
]
Here is the php i use to generate the json:
$rows = array();
while($r = $result->fetch_assoc())
{
$rows[] = $r;
}
echo json_encode($rows, JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT);

You could serve it in the form of a 2d array, but I don't think it makes much of a difference.
Simple example to make that happen:
$rows = array();
while($r = $result->fetch_assoc())
{
$rows[$r["name"]][] = $r["id"];
}
echo json_encode($rows);
Which would give you an array grouped by names.
Also, seeing as this output is sent to the browser, it should be minified.
The user doesn't (at least, doesn't need to) see the actual JSON report, it is used by his browser as JavaScript variables.
Because of that, there's no benefit in providing a prettified version, plus, you're bloating the content length and use more bandwidth.
Bottom Line: Server JSON as compressed and minified as possible.

Related

PHP and JSON - extra comma in results

I'm trying to return json response in the correct format but I am getting an extra 'comma' in the returned code (comma after the last item 'Pencil'):
{
"results": [{
"ItemID": 1,
"ItemName": "Ball"
}, {
"ItemID": 2,
"ItemName": "Pen"
}, {
"ItemID": 3,
"ItemName": "Pencil"
},
}]
}
I tried different things but I can't get rid of it. Would anybody have any idea how to remove it?
The code that i have is this:
<?php
print '{"results":[';
for ($i=0; $i <$numrows; $i++) {
$stmt->fetch();
$JSONArray = array(
"ItemID" => $ItemID,
"ItemName" => $ItemName
);
print ",";
print json_encode($JSONArray);
}
print "]}"
?>
You're doing it ENTIRELY wrong. You're outputting multiple independent JSON strings, which is outright wrong. JSON is a monolithic "structure", and building it piece-wise is highly risky.
Simple: DOn't do that.
You build a standard PHP array, then do ONE SINGLE encoding when you're completely done building:
$arr = array();
for(...) {
$arr[] = ... add stuff ..
}
echo json_encode($arr);
First, fetching into bound variables is causing you an extra step, second, you don't need to construct any JSON. Just get all of your rows into the proper array structure and encode:
$result = $stmt->get_result();
while($rows['results'][] = $result->fetch_array(MYSQLI_ASSOC)){}
echo json_encode($rows);
If your system supports it, just use this instead of the while loop:
$rows['results'] = $result->fetch_all(MYSQLI_ASSOC);

json_encode - formatting issue?

I am requesting my output look like this:
Response
{
error_num: 0
error_details:
[
{
"zipcode": 98119
},
{
"zipcode": 98101
}
]
}
The values are irrelevant for this example.
My code looks like this:
$returndata = array('error_num' => $error_code);
$returndata['error_details'] = $error_msg;
$temp_data = array();
$temp_value = '';
foreach ($zipcodes_array as $value) {
//$temp_data['zipcode'] = $value;
//$temp_value .= json_encode($temp_data);
$temp_value .= '{"zipcode":$value},';
}
//$returndata['test'] = $temp_value;
$returndata['zipcodes'] = $temp_value;
echo json_encode($returndata);
My output varies depending on my different attempts (which you can see with the commented out things) but basically, I don't understand how the 3rd part (the part with the zipcodes) doesn't have a key or a definition before the first open bracket "["
Here is the output for the code above:
{"error_num":0,"error_details":"","zipcodes":"{\"zipcode\":11111},{\"zipcode\":11112},{\"zipcode\":11113},{\"zipcode\":22222},{\"zipcode\":33333},{\"zipcode\":77325},{\"zipcode\":77338},{\"zipcode\":77339},{\"zipcode\":77345},{\"zipcode\":77346},{\"zipcode\":77347},{\"zipcode\":77396},{\"zipcode\":81501},{\"zipcode\":81502},{\"zipcode\":81503},{\"zipcode\":81504},{\"zipcode\":81505},{\"zipcode\":81506},{\"zipcode\":81507},{\"zipcode\":81508},{\"zipcode\":81509},"}
Obviously i did not show the variables being filled/created because its through MySQL. The values are irrelevant. Its the format of the output i'm trying to get down. I don't understand how they have the "zipcode": part in between {} brackets inside another section which appears to be using JSON_ENCODE
It is close but see how it still has the "zipcodes": part in there defining what key those values are on? My question is, is the "response" above being requested by a partner actually in JSON_ENCODE format?? or is it in some custom format which I'll just have to make w/out using any json features of PHP? I can easily write that but based on the way it looks in the example above (the response) I was thinking it was JSON_ENCODE being used.
Also, it keeps putting the \'s in front of the " which isn't right either. I know it's probably doing that because i'm json_encode'ing a string. Hopefully you see what i'm trying to do.
If this is just custom stuff made to resemble JSON, I apologize. I've tried to ask the partner but I guess i'm not asking the right questions (or the right person). They can never seem to give me answers.
EDIT: notice my output also doesn't have any [ or ] in it. but some of my test JSON_ENCODE stuff has had those in it. I'm sure its just me failing here i just cant figure it out.
If you want your output to look like the JSON output at the very top of your question, write the code like this:
$returndata = array('error_num' => $error_code);
$returndata['error_details'] = array();
foreach ($zipcodes_array as $value) {
$returndata['error_details'][] = array('zipcode' => (int)$value);
}
echo 'Response ' . json_encode($returndata);
This will return JSON formatted like you requested above.
Response
{
error_num: 0
error_details:
[
{
"zipcode": 98119
},
{
"zipcode": 98101
}
]
}
Can you just use single ZipCode object as associative array, push all your small ZipCode objects to the ZipCodes array and encode whole data structure. Here is the code example:
$returndata = array(
'error_num' => $error_code,
'error_details' => array()
);
foreach ($zipcodes_array as $value) {
$returndata['error_details'][] = array('zipcode' => $value);
}
echo json_encode($returndata);

How to create json with objects as element from mysql multiple rows

Hi I pretty much stuck on creating json using php and mysql. I got lots of similar question and answers here but I cannot get what I want even after spending lots of time.I need my json output from mysql rows to be like
{ "application": [ { "ver": "1.0", "name": "myapp1" }, { "ver": "1.2", "name": "myapp2"}]}
I used following code for generating json,
$result=mysql_query("SELECT * FROM btrack_transaction");
$no_of_rows = mysql_num_rows($result);
$rows = array();
//retrieve and print every record
while($r = mysql_fetch_assoc($result)){
$rows[] = array('data' => $r);
}
// now all the rows have been fetched, it can be encoded
echo json_encode($rows);
But my output looks like
[[ { "ver": "1.0", "name": "myapp1" }, { "ver": "1.2", "name": "myapp2"}]]
How can I get the json format that I want .
Thanks in advance ,
while ($r = mysql_fetch_assoc($result)) {
$rows[] = $r;
}
echo json_encode(array('application' => $rows));
You need to get rid of the extra array('data' => $r) wrapper around each element (I don't know why that doesn't show up in the output you say you get), and add the array('application' => $rows) at the end to add that element.

json_encode output in PHP not giving the data a label so it can be accessed

I am currently trying to pull existing data from my database to use on a page in real time,
I have a PHP file called json.php that use's the following code.
$sth = mysql_query("SELECT * FROM table ORDER BY id DESC");
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
print json_encode($rows);
Which then outputs.
[
{
"id": "1",
"title": "1",
"img": "1.jpg"
},
{
"id": "2",
"title": "2",
"img": "2.png"
}
]
But as Im trying to learn online every example I see seems to have a label for each 'object' from the JSON then is called using something like,
json.label.title
How comes the PHP function doesn't print out a label so I can access the data in jQuery? Or have I done something wrong with my tables in MySQL?
As I said above I have tried researching online to learn how to do this but on every example I keep running into this problem.
Your JSON represents an array holding objects.
for (var i = 0; i < json.length; i++)
json[i].title; // your value
[...] is an array with numeric indexes (from 0 to array.length - 1) and {...} an object with string labels.

Manipulating data from a JSON feed to display it

{
"Group": [
{
"name": "HolderOne",
"operators": [
{
"username": "ken",
"status": 3
},
.....etc.....
The JSON feed I am attempting to manipulate has to format above.
I wish to be able to display username and status.
$json = file_get_contents("urlhere");
$obj=json_decode($json);
echo $obj->username;
echo $obj->status;
This obviously doesn't work as they are nested(?) within the feed...I have tried:
$obj->Group[0]->name->operators->username
and
$obj->Group[0]->name->username
to no avail (as well as json_decode with ,true and ['name'], etc).
Am I being particularly dim?
when I do a var dump, the data is being collected from the feed okay.
The best way to figure this out is to iteratively do print_r's:
print_r($obj)
//prints what you see above
print_r($obj['Group']
//prints the Group Object
print_r($obj['Group'][0])
//prints first element in Group Object
print_r($obj['Group'][0]['operators'])
//etc.....
That's how I find out how to access these deep elements if I get a little stuck. Though it appears to me that you want:
$obj->Group[0]->operators[0]->username

Categories