HI im having a little difficulty with dataTables and php. I'm echoing out json in the format below:
{"iTotalRecords":10,"iTotalDisplayRecords":10,"aaData":[[ "1", "15","1","long description long description long description long description"," 2012-02-25 00:00:00"],[ "1", "15","1","long description long description long description long description"," 2012-02-25 00:18:59"] ... ] }
Which inst working with my dataTable, However after validating the above in jsonlint.com/, i get the well formated version below:
{
"iTotalRecords": 10,
"iTotalDisplayRecords": 10,
"aaData": [
[
"1",
"15",
"1",
"long description long description long description long description",
"2012-02-25 00:18:59"
],
...
]
}
When I put this in a txt file it loads just fine. I also noticed that adding a line break in the "long description" part, it also doesn't work even with the one above. My guess is that the line break is messing with the format of the json, but how can I avoid this in my php script since everything is being word wrapped? I've tried \n in my echo code but it doesnt seem to create a newline.
The opening and closing curly braces { and } are not acceptable to DataTables. My guess is, it's considered an object rather than an array. Try this:
Use the following php function to create your JSON array:
$this->arrayJSON = $this->arrayPHPToJS($myArray);
public function arrayPHPToJS($phpArray) {
if (is_null($phpArray)) return 'null';
if (is_string($phpArray)) return "'" . $phpArray . "'";
if (self::is_assoc($phpArray)) {
$a=array();
foreach ($phpArray as $key => $val )
$a[]=self::arrayPHPtoJS($val);
return "[" . implode ( ', ', $a ) . "]";
}
if (is_array($phpArray)) {
$a=array();
foreach ($phpArray as $val )
$a[]=self::arrayPHPtoJS($val);
return "[" . implode ( ', ', $a ) . "]";
}
return json_encode($phpArray);
}
Use this array in JS script in your view (make sure there's no html escaping):
<script type="text/javascript">
var jsArray = <?php echo $arrayJSON; ?>;
$(function(){
var oTable = $('#mytable').dataTable( {
"aaData": jsArray,
....
});
});
</script>
sounds more like the number of columns set up in table/datatables doesn't match number of items in your json array
There seemsed to be an issue with one of my database values, it was starting on a new line, which cause the format of the json to be incorrect.
Related
i have a regex challenge i can't solve on my own, i have a json stringified file that hold lots of entries so instead of decoding it and looping over all items i want just use a preg_replace to delete a specific item with specific id.
so my json look like this:
[
{
"id":"440",
"type":"prospect",
"fullname":"elizabeth cogelizabeth",
"phone":"01768413081",
"..." : ""
},
{
"id":"436",
"type":"prospect",
"fullname":"mandy cogmandy",
"phone":"01697349008",
"..." : ""
}
]
what i know is the id part so i can do something like this
preg_replace('/{\"id\"\:\"440\".*?\"},/', '', $jsonBlob);
unfortunately my regex don't keep in count the last item that doesn't end with comma , but with a bracket ]
any help is really appreciated. thanks in advance.
Loop through JSON example using the id, in your case you don't need to use unset().
$json = '[
{
"id":"440",
"type":"prospect",
"fullname":"elizabeth cogelizabeth",
"phone":"01768413081",
"..." : ""
},
{
"id":"436",
"type":"prospect",
"fullname":"mandy cogmandy",
"phone":"01697349008",
"..." : ""
}
]';
$arr = json_decode($json,true);
foreach($arr as $key => $value) {
if($value['id']==436) {
unset($arr[$key]); // delete this entry from results
// $value = your_new_json_object {id,type,..}
}
}
print_r($arr);
Fiddle
Would you mind to try this Function and see if it does the trick for you?
<?php
// PASS IN THE ID YOU WANNA FILTER-OUT AS $id,
// 2ND PARAMETER IS THE JSON STRING
// 3RD PARAMETER IS THE REPLACEMENT STRING: IN YOUR CASE EMPTY: ""
function removeJsonBlock($id, $jsonSTR, $replacement="YEAH!!! IT WORKS!!!"){
$jsonSTR = trim($jsonSTR);
$filteredJson = preg_replace('#(\{\s*)([\'\"]id[\'\"]\:)(\s?[\'\"])' . trim($id) . '([\'\"])([\w,\.;\"\'\-\?\:\s_\n\r]+)(\},?)#si', $replacement, $jsonSTR);
return $filteredJson;
}
// THE JSON STRING IN QUESTION - REGARDLESS OF WHETHER DYNAMIC OR NOT.
$jsonSTR =<<<JSS
[
{
"id":"440",
"type":"prospect",
"fullname":"elizabeth cogelizabeth",
"phone":"01768413081",
"..." : ""
},
{
"id":"436",
"type":"prospect",
"fullname":"mandy cogmandy",
"phone":"01697349008",
"..." : ""
},
// ADD ANOTHER NODE WITH THE SAME ID OF 440 FOR EXAMPLE...
{
"id":"440",
"type":"prospect",
"fullname":"elizabeth cogelizabeth",
"phone":"01768413081",
"..." : ""
},
]
JSS;
// TEST THE SIMULATION... IT SHOULD REMOVE EVERY ENTRY WITH ID: 440
var_dump(removeJsonBlock(440, $jsonSTR));
//
I hope it helps in a little bit.... ;-)
You can use this regex:
{\s*"id":"440"[^}]*}
As a string that's:
$re = "/{\\s*\"id\":\"440\"[^}]*}/im";
This assumes that id is the first value in the JSON array, but it will account for whitespace. It uses [^}]* to grab everything up to the }.
Since you're looking to delete the item, the regex can be changed to look for commas before or after the match. I have also included a way for the item to match if it is the only thing in the array:
,\s*{\s*"id":"440"[^}]*}|{\s*"id":"440"[^}]*}\s*,|{\s*"id":"440"[^}]*}
It's easier to read with x spacing enabled:
,\s*{\s*"id":"440"[^}]*} |
{\s*"id":"440"[^}]*}\s*,|
{\s*"id":"440"[^}]*}
I need to parse a JSON file. I've only worked with XML before.
How can I get the second "food_id" (1730905)?
Here is my JSON file:
{
"shopId":29,
"last":46977914,
"freshfood":[
{
"freshfood_id":2629,
"food":[
{
"food_id":1740851,
"type":"fruit",
"status":1
},
{
"food_id":1730905,
"type":"vegetable",
"status":1
},
]
}
]
}
I tried this, but it does not work.
$string = file_get_contents("food.json");
$json_a=json_decode($string,true);
echo $GetFreshFoodId = $json_a['freshfood'][1]['freshfood_id'];
PHP arrays are zero-based, so that should be:
$json_a['freshfood'][0]['food'][1]['food_id'];
Also, note that the JSON is not entirely valid - you should remove the last comma. (But you might have left out additional records in your example JSON for clarity.)
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);
I've been having issues trying to parse this json data.
I tried to do this to return the name but its not working:
foreach(json_decode($test) as $item){
$name= $item->users->name;}
This is the json code:
{
"users":[
{
"id":"dsfdfsd",
"id_str":"dsfsdf",
"name":"Davy",
"screen_name":"Davy232",
"location":"Colorado"
},
{
"id":"wer",
"id_str":"wer",
"name":"Sarah",
"screen_name":"Davy232",
"location":"LA"
},
{
"id":"fdf",
"id_str":"fdf",
"name":"James",
"screen_name":"James374",
"location":"Vegas"
}
]
}
That is because the JSON is invalid , Here's the proper fixed JSON
Fixed JSON Data
{
"users":[
{
"id":"dsfdfsd",
"id_str":"dsfsdf",
"name":"Davy",
"screen_name":"Davy232",
"location":"Colorado"
}
]
}
What were the problems ?
You did not surround dsfdfsd with doubles quotes.
There was an extra comma after Colorado
The braces were not properly balanced.
Also, your foreach should be like this..
foreach(json_decode($test) as $item){
echo $item[0]->name;
}
Working Demo - Part 1
Working Demo - Part 2
I cannot figure out json for whatever reason, i don't understand why i cannot get this to work.
my json is returning:
{"lists":[{"item":"1","count":"5"}]}
{"lists":[{"item":"1","count":"5"}]}
{"lists":[{"item":"1","count":"5"}]}
{"lists":[{"item":"1","count":"5"}]}
{"lists":[{"item":"1","count":"5"}]}
etc, etc, etc
now i am trying to retrieve it by using:
$.getJSON("lists.php",
{id: aid},function(data){
$.each(data.lists, function(i, info) {
$('.container').append(info.item+info.count);
});
});
but i don't get any data here. can anyone point me in the right direction?
});
You need to return the data like this:
{
"lists":[
{"item":"1","count":"5"},
{"item":"1","count":"5"},
{"item":"1","count":"5"},
{"item":"1","count":"5"},
{"item":"1","count":"5"}
]
}
In your php, do the following:
echo "{\"lists\":[";
foreach ($lists as $obj) {
echo "{\"item\": \"" . $obj->item . "\", ";
echo "\"count\": \"" . $obj->count . "\"},";
}
echo "]}\n";
Hope that helps!
It looks like you're used to how URL parameters are encoded. JSON works differently.
If you want your object to contain a key lists which contains an array, you should return JSON like this:
{
"lists": [
{"item":"1","count":"5"},
{"item":"1","count":"5"},
{"item":"1","count":"5"},
{"item":"1","count":"5"},
{"item":"1","count":"5"}
]
}
The above isn't valid JSON. I believe this is the syntax you are looking for, which would be described as "an object with a list property containing an array of items":
{"lists":[{"item":"1","count":"5"},{"item":"1","count":"5"},{"item":"1","count":"5",{"item":"1","count":"5"},{"lists":[{"item":"1","count":"5"}]}
You probably need to adjust your backend code so it's adding a new member to the "lists" array rather than an entirely new "lists" each time.