Is my JSON correct? - json

I've implemented a JSON and an RSS feed into FullCalendar [only currently pulling events from JSON]. Using CodeIgniter I've created my JSON using the following code
<?php
$jsonevents = array();
foreach($events->result() as $entry){
$jsonevents[] = array(
'id' => $entry->eventID,
'title' => $entry->eventTitle,
'start' => $entry->startDate,
'end' => $entry->endDate,
'allDay' => false
);
}
echo json_encode($jsonevents);
?>
The following outputs this JSON
[{"id":"1234567891","title":"Test 3","start":"2011-05-07 00:00:00","end":"2011-05-13 00:00:00","allDay":false},
{"id":"24242","title":"sdfsdfsdfsdf","start":"2011-05-05 13:00:53","end":"2011-05-06 17:00:19","allDay":false},
{"id":"1234567890","title":"Test","start":"2011-05-05 13:00:53","end":"2011-05-06 17:00:19","allDay":false}]
The issue is when imported into FullCalendar it creates an event within an event, I believe it might have something to do with the square brackets, but I'm unsure of how to correct the output, anyone have any ideas?

Your json is right.
I've validated it with http://json.bloople.net/
You may have another problem when applying it to your calendar plugin.

I've just formatted your json string with JSON Formatter & Validator and it's valid.
The square brackets mean that the whole thing is an array. Please refer to json.org.

Json is right.. yay.
I also had this problem ;)
Make all day True and look below on the time.
2011-05-07 00:00:00
try notice the 'T'
2011-05-07T00:00:00
Here is a sample of my complex feed
[{"title":"Tee Times","start":"2011-05-03T00:00:00","end":"2011-05-03T00:00:00","allDay":true,"color":"rgb(21,144,51)","groupsize":"","className":"data-brs clickable","cache":null,"EventName":null,"description":null,"EventCompTypeMSP":null,"url":null,"CompName":null,"CompCourseName":null,"CompNumberDivs":null,"CompQualifierYN":null,"CompNumber":null},{"title":"Tee Times","start":"2011-05-04T00:00:00","end":"2011-05-04T00:00:00","allDay":true,"color":"rgb(21,144,51)","groupsize":"","className":"data-brs clickable","cache":null,"EventName":null,"description":null,"EventCompTypeMSP":null,"url":null,"CompName":null,"CompCourseName":null,"CompNumberDivs":null,"CompQualifierYN":null,"CompNumber":null},{"title":"Tee Times","start":"2011-05-05T00:00:00","end":"2011-05-05T00:00:00","allDay":true,"color":"rgb(21,144,51)","groupsize":"","className":"data-brs clickable","cache":null,"EventName":null,"description":null,"EventCompTypeMSP":null,"url":null,"CompName":null,"CompCourseName":null,"CompNumberDivs":null,"CompQualifierYN":null,"CompNumber":null},{"title":"Tee Times","start":"2011-05-06T00:00:00","end":"2011-05-06T00:00:00","allDay":true,"color":"rgb(21,144,51)","groupsize":"","className":"data-brs clickable","cache":null,"EventName":null,"description":null,"EventCompTypeMSP":null,"url":null,"CompName":null,"CompCourseName":null,"CompNumberDivs":null,"CompQualifierYN":null,"CompNumber":null},{"title":"","start":"2011-05-03T07:10:00","end":"2011-05-03T08:00:00","allDay":false,"color":"rgb(21,144,51)","groupsize":"","className":"data-brs clickable","cache":null,"EventName":null,"description":null,"EventCompTypeMSP":null,"url":null,"CompName":null,"CompCourseName":null,"CompNumberDivs":null,"CompQualifierYN":null,"CompNumber":null},{"title":"Test","start":"2011-05-04T07:00:00","end":"2011-05-04T07:50:00","allDay":false,"color":"rgb(21,144,51)","groupsize":"","className":"data-brs clickable","cache":null,"EventName":null,"description":null,"EventCompTypeMSP":null,"url":null,"CompName":null,"CompCourseName":null,"CompNumberDivs":null,"CompQualifierYN":null,"CompNumber":null},{"title":"Riley","start":"2011-05-04T08:00:00","end":"2011-05-04T08:00:00","allDay":false,"color":"rgb(21,144,51)","groupsize":"4","className":"data-brs clickable","cache":null,"EventName":null,"description":null,"EventCompTypeMSP":null,"url":null,"CompName":null,"CompCourseName":null,"CompNumberDivs":null,"CompQualifierYN":null,"CompNumber":null},{"title":"Test","start":"2011-05-04T08:10:00","end":"2011-05-04T17:50:00","allDay":false,"color":"rgb(21,144,51)","groupsize":"","className":"data-brs clickable","cache":null,"EventName":null,"description":null,"EventCompTypeMSP":null,"url":null,"CompName":null,"CompCourseName":null,"CompNumberDivs":null,"CompQualifierYN":null,"CompNumber":null},{"title":"pea","start":"2011-05-05T08:10:00","end":"2011-05-05T08:10:00","allDay":false,"color":"rgb(21,144,51)","groupsize":"1","className":"data-brs clickable","cache":null,"EventName":null,"description":null,"EventCompTypeMSP":null,"url":null,"CompName":null,"CompCourseName":null,"CompNumberDivs":null,"CompQualifierYN":null,"CompNumber":null},{"title":"peter","start":"2011-05-06T07:10:00","end":"2011-05-06T07:10:00","allDay":false,"color":"rgb(21,144,51)","groupsize":"1","className":"data-brs clickable","cache":null,"EventName":null,"description":null,"EventCompTypeMSP":null,"url":null,"CompName":null,"CompCourseName":null,"CompNumberDivs":null,"CompQualifierYN":null,"CompNumber":null},{"title":"March Medal - Mens Medal - CSS: 70 - PAR: 70 - Click for more info...","start":"2011-03-15T00:00:00","end":null,"allDay":null,"color":"rgb(10,87,164)","groupsize":null,"className":"data-previous clickable","cache":null,"EventName":null,"description":null,"EventCompTypeMSP":null,"url":"http://www.howdidido.co.uk/ClubDetails.aspx?section=24&pagesection=compresultsdetails&compid=383","CompName":"March Medal","CompCourseName":"White Tee's","CompNumberDivs":1,"CompQualifierYN":"N","CompNumber":383}]

Related

Parse JSON to table (Wordpress)

I am looking at parsing some data from JSON and or XML into a table.
I am looking for someone to help me with the basics of this. I need to parse multiple items form the JSON or XML into the table. Below I give my JSON example:
{"appartments":[{"aptnum":"199","design":"open","sqft":"1200","extras":"covered parking","pool":"yes","moveinDate":"2019-01-01 13:12:01","link":"https:\/\/www.demoapts.com\/demo\/199"},{"aptnum":"223","design":"Built Already","sqft":"1800","extras":"covered parking","pool":"yes","moveinDate":"2018-05-09 00:12:01","link":"https:\/\/www.demoapts.com\/demo\/223"}]
What I need help with is parsing this data to a html/Wordpress table.
I also am using a special type of button but I think I have that figured out if I can learn how to parse the data correctly.
I am hoping some of you can help me and point me in the right direction. I have searched on Google and I have only found examples of parsing one item from the JSON.
Here is an example on how you can parse this JSON structure into a table
<?php
$data = json_decode('{"appartments":[{"aptnum":"199","design":"open","sqft":"1200","extras":"covered parking","pool":"yes","moveinDate":"2019-01-01 13:12:01","link":"https:\/\/www.demoapts.com\/demo\/199"},{"aptnum":"223","design":"Built Already","sqft":"1800","extras":"covered parking","pool":"yes","moveinDate":"2018-05-09 00:12:01","link":"https:\/\/www.demoapts.com\/demo\/223"}]}');
// Convert JSON string into a PHP object.
$appartments = $data->appartments;
echo('<table>');
if(!empty($appartments)){
echo('<thead><tr>');
// Using the first object to print column names.
foreach($appartments[0] as $key => $value){
echo('<th>' . $key . '</th>');
}
echo('</tr></thead>');
echo('<tbody>');
// Iterate through all appartments and print them as table cells.
foreach($appartments as $appartment){
echo('<tr>');
foreach($appartment as $key => $value){
echo('<td>' . $value . '</td>');
}
echo('</tr>');
}
echo('</tbody></table>');
}
?>

formatter asDateTime in yii2

If I have an element array like this :
[PERKIRAAN_SELESAI] => 24/10/2016 09:38
Then I want to store into datetime format in mysql which is YYYY-MM-DD H:s,
=> 2016-10-24 09:38
How can Yii2 handle this,
Now, in beforeSave(), I use this :
$this->perkiraan_selesai = Yii::$app->formatter->asDateTime(strtorime($this->PERKIRAAN_SELESAI), "php:Y-m-d H:s" );
But, still not working.
Please.
First of all, I see 2 errors in your code:
2016-10-24 09:38 date looks like a Y-m-d H:i format, not Y-m-d H:s. Check PHP date function docs for interpretation of these letters.
strtorime must be strtotime, but I think this typo is not in original code, just here in post.
As for your problem, check this related question on SO. Seems that the problem is with handling of slash (/). Instead of replacing it with - manually, I found solution with native class DateTime much better.
Using plain PHP:
$date = \DateTime::createFromFormat('d/m/Y H:i', '24/10/2016 09:38')->format('Y-m-d H:i');
Using Yii2 formatter:
$date = Yii::$app->formatter->asDateTime(\DateTime::createFromFormat('d/m/Y H:i', '24/10/2016 09:38'), 'php:Y-m-d H:i');
Just replace this date with your value.
The value of $date is 2016-10-24 09:38 as expected.

GetMapping not working for Nest client in Elasticsearch

perhaps some of the documentation http://nest.azurewebsites.net/ is old because i'm running into a at least few issues...
i've got a json object 'search'. i am getting null returned from the GetMapping function. well, it returns a Nest.RootObjectMapping object, but all fields within are null. i can get the mapping fine using Sense or regular curl.
var mapping = elasticClient.GetMapping<MyJsonPOCO>();
any ideas?
also, just as example of other things going wrong, this search works, but adding 'fields' to it does not (i got the fields declaration per the documentation)
var result = elasticClient.Search<MyJsonPOCO>(s => s
.Query(q => q
.QueryString(qs => qs
.OnField(e => e.Title)
.Query("my search term"))));
if i use this query with the fields added (to just return 'title'), i get a json parser issue.
var result = elasticClient.Search<MyJsonPOCO>(s => s
.Fields(f => f.Title)
.Query(q => q
.QueryString(qs => qs
.OnField(e => e.Title)
.Query("my search term"))));
here's the error for that one:
An exception of type 'Newtonsoft.Json.JsonReaderException' occurred in Newtonsoft.Json.dll but was not handled in user code
Additional information: Error reading string. Unexpected token: StartArray. Path 'hits.hits[0].fields.title', line 1, position 227.
Elasticsearch 1.0 changed the way fields are returned in the search response
You need the NEST 1.0 beta1 release to work with Elasticsearch 1.0
http://www.elasticsearch.org/blog/introducing-elasticsearch-net-nest-1-0-0-beta1/
See also this github issue for more background information on the why and how to work with fields from 1.0 forward:
https://github.com/elasticsearch/elasticsearch-net/issues/590

Decode a JSON file with PHP

I have a classic JSON problem, and i know that many post are asking about that...
But i doubt that the JSON i try to grab has a correct structure.
The files Begin like that :
[{
"time":"0-12h",
"articles":[
{
"id":1,
"domain_id":22,
"title":"Hi Guys"
}
{
"id":2,
"domain_id":17,
"title":"Hi everyone"
}
]
}]
I have try a lot of combinaison to echo the title :
$data = json_decode($json, true);
echo $data->articles;
Or
echo $data->articles->title;
Or
echo $data->articles[0]->title;
Nothing works... :(
Can you help me ?
Thanks !
The second argument true to json_decode() means it should create associative arrays rather than objects for {} in the JSON. So in addition to dealing with the indexed arrays as Explosion Pills points out, you also need to use array syntax to access the keyed elements:
$data[0]['articles'][0]['title']
If you want to be able to use -> syntax, leave out the second argument or set it to false.
I'm hoping the missing comma in the JSON is an error when transcribing to the question. If not, you also need to fix the code that creates the JSON in the first place.
$data itself is an array. Try
$data[0]->articles[0]->title;
Also the JSON is not valid (missing a comma before the second articles array element).
there is a comma , missing
}
,
{
json_decode with the second parameter true returns an array
print_r($data['articles']);
echo $data['articles'] would output Array

Data column(s) for axis #0 cannot be of type string error in google chart

I tried to populate google chart datatable in server side using PHP.I got JSON file properply, but the Chart not display in client Application. I got error-Data column(s) for axis #0 cannot be of type string . My coding is below here.
After fetching data from database,
$colarray=array(array("id"=>"","label"=>"userid","pattern"=>"","type"=>"number"),array("id"=>"","label"=>"name","pattern"=>"","type"=>"string"));
$final=array();
for($i=0;$i<$rows;$i++)
{
$id[$i]=pg_fetch_result($res1,$i,'id');
$name[$i]=pg_fetch_result($res1,$i,'name');
$prefinal[$i]=array("c"=>array(array("v"=>$name[$i]),array("v"=>$name[$i])));
array_push($final,$prefinal[$i]);
}
$table['cols']=$colarray;
$table['rows']=$final;
echo json_encode($table);
My Output Json:
{
"cols":[
{"id":"","label":"userid","pattern":"","type":"number"},
{"id":"","label":"name","pattern":"","type":"string"}
],
"rows":[
{"c":[{"v":"101"},{"v":"Aircel"}]},
{"c":[{"v":"102"},{"v":"Srini"}]},
{"c":[{"v":"103"},{"v":"Tamil"}]},
{"c":[{"v":"104"},{"v":"Thiyagu"}]},
{"c":[{"v":"105"},{"v":"Vasan"}]},
{"c":[{"v":"107"},{"v":"Senthil"}]},
{"c":[{"v":"108"},{"v":"Sri"}]},
{"c":[{"v":"109"},{"v":"Docomo"}]},
{"c":[{"v":"106"},{"v":"Innodea"}]}
]
}
How to solve this issue?
To extend on #sajal's accurate answer: Change the last line of your code from:
echo json_encode($table);
to:
echo json_encode($table, JSON_NUMERIC_CHECK);
This will tell json_encode to recognize numbers and abstain from wrapping them in quotes (Available since PHP 5.3.3.).
http://php.net/manual/en/json.constants.php#constant.json-numeric-check
You specify type of userid as number... but pass string.. thats causing the problem.
I just wasted 30 mins with the opposite problem ...
Your output json should look like :-
{
"cols":[
{"id":"","label":"userid","pattern":"","type":"number"},
{"id":"","label":"name","pattern":"","type":"string"}
],
"rows":[
{"c":[{"v":101},{"v":"Aircel"}]},
{"c":[{"v":102},{"v":"Srini"}]},
{"c":[{"v":103},{"v":"Tamil"}]},
{"c":[{"v":104},{"v":"Thiyagu"}]},
{"c":[{"v":105},{"v":"Vasan"}]},
{"c":[{"v":107},{"v":"Senthil"}]},
{"c":[{"v":108},{"v":"Sri"}]},
{"c":[{"v":109},{"v":"Docomo"}]},
{"c":[{"v":106},{"v":"Innodea"}]}
]
}
On a BarChart, one of the columns (the second one) has to be a number. That can cause this error message.
In your drawChart() function, you are probably using google.visualization.arrayToDataTable, and this does not allow any nulls. Please use addColumn function explicitly
If the Data format should be like:
data: [
["string", "string"], //first Column
["string1", number],
["string2", number],
["string3", number],
]
then you can overcome this error.
when you are passing your data from controller you need to do like so: just take an example I have controller and I am sending data through it via group by.
controller:
\DB::statement("SET SQL_MODE=''");//this is the trick use it just before your query
$Rspatients = DB::table('reports')
->select(
DB::raw("day(created_at) as day"),
DB::raw("Count(*) as total_patients"))
->orderBy("created_at")
->groupBy(DB::raw("day(created_at)"))
->get();
$result_patients[] = ['day','Patients'];
foreach ($Rspatients as $key => $value) {
$result_patients[++$key] = [$value->day,$value->total_patients];
}
return view('Dashboard.index')
->with('result_patients',json_encode($result_patients,JSON_NUMERIC_CHECK));
if there is no JSON_NUMERIC_CHECK, so the data will be array of strings while if there is json check the data will be converted to array of numbers.
before JSON check data:
4: (2) ["24", "413"]
5: (2) ["25", "398"]
After JSON Check data:
4: (2) [24, 413]
5: (2) [25, 398]