Unable to convert String to JSON for google charts - json

Can any body explain me how to parse the below code in JSON. When I remove {type: 'string', role: 'tooltip'} and \"huu\", I am able to generate the chart
Code Snippet :
var obj=JSON.parse("[[\"Carrier Name\",{type: 'string', role: 'tooltip'}, \"Transactions\", \"Spending\", \"Chargeable Weight\"], [\" - AK - AirAsia Berhad dba AirAsia\",\"huu\", 15, 0.8778833367217757, 0.9236859587487404]]");
var data = google.visualization.arrayToDataTable(obj);

{type: 'string', role: 'tooltip'} is a syntax error from JSON perspective. You should change that part to {"type": "string", "role": "tooltip"}. I did not face any problems with "huu" when I validated the JSON string using JSOnLint. JSONLint may not work on recent FF. Use chrome.

Related

adding json element in json file

I have a json file in my android local device, im able to read and edit the json file and store json data in it.
But the problem is arising when i want to insert new element in the json file. Im able to change the value of existing variables.
the json file data is:
var data = {items:
{id: "1", name: "Snatch", type: "crime"}
};
i want to add one more element to it so that json file will look like
var data = {items: [
{id: "1", name: "Snatch", type: "crime"},
{id: "7", name: "Douglas Adams", type: "comedy"}
};
i tried with
data.items.push{id: "7", name: "Douglas Adams", type: "comedy"}
but its not working.
im creating android app using phonegap framework with telerik IDE.
Try
data.items.push(
{id: "7", name: "Douglas Adams", type: "comedy"}
);
You are missing ()
Your first file example is missing []
Check out this links to know more about json addition and removal
Link 1 , Link 2

jqgrid Toolbar search on custom formatted column

I am loading JQGrid from an API, one of the data structures that I have for my grid is a JSON element formatted as such:
{"id":123,"name":"John Doe","username":"john.doe"}
The data is properly displayed in the grid, however if I try to type in the toolbar search, I do not get a match presumably because jqgrid still has the above JSON stored as an object.
A truncated version of my grid is as follows:
$('#test').jqGrid({
...
loadonce: true,
datatype: 'local',
colModel: [
{name:'test', index:'test', label:'Test', formatter:customFormatter}
],
...
});
function customFormatter (cellvalue,options) {
return cellvalue.name;
}
I found this post that seems to address this very matter, however I am struggling to get my head around as to how to use this for a JSON object. Once the grid is loaded, I don't see a reason as to why the local data should be anything other than string (Until the grid is reloaded).
After stumbling upon the JSON dot notation in the docs, and adding it to the index this now works:
colModel: [
{name:'test.name', index:'test.name', label:'Test'}
]
You should choose name property of colModel which corresponds the names of the properties in the JSON input. So it's native to use just
colModel: [
{name: "name", label: "Name"}
{name: "username", label: "User Name"}
]
If you do need to remap some names in the JSON input to another names in the colModel you should use jsonmap property. For example
colModel: [
{name: "test1", label: "Name", jsonmap: "name"}
{name: "test2", label: "User Name", jsonmap: "username"}
]
The usage of index different as name is not possible in case of usage of loadonce: true. It is not recommended to use values of name property which have . or any other meta-character. The restriction exist because the name property will be used to build id property of many elements of the grid.

In ExtJS, how to define jsonreader for different json input formats?

I have an external source that generates JSON in given format. I need to use ScriptTagProxy to access that data. Format of data is (two records):
{
"COLUMNS":["KEDBID","EMPID","KE","SOLUTION","ATTACH_KE","ATTACH_SOLUTION"],
"DATA":[
[1,36661,"While adding a new user, if his\/her profile is missing, it could be LDAP server issue.","Contact Mr. ABC from infra team to get user's profile corrected on server","screenshots.jpg","conacts.doc"],
[2,36661,"The error code # 123445 is trivial that may occur at particular time.","To resolve this issue, we will need to ask DBA team to refresh database. That will fix this type of errors","NA","NA"]
]
}
How to define jsonreader for this data? As i have seen that root should be like:
{ROOT: [ {field1:data1,field2:data1},{field1:data2,field2:data2}]}
while my JSON is like:
{fieldnames:['field1','field2'],
ROOT:[ [data1ForField1,data1ForField2],[data2ForField1,data2ForField2] ]
}
UPDATE
Adding one more case:
Similarly can we have a jsonreader for;
{"ROWCOUNT":8,
"COLUMNS":["CATID","CATEGORY"],
"DATA":{"CATID":[1,2,3,4,5,6,7,8],"CATEGORY":["Optimization","Automation","Process Improvement","Tool","Other","Another One","ThisHas'","More^!##(){}"]}}
where 1-->Optimization, 2-->Automation, 3-->Process Improvement etc.
Basically I need to return data from ColdFusion query object by serializing query object. Serialization in CF Query can return data in above two formats.
I'm still new to Ext World!! Hope to get some support.
Best Regards,
Tushar Saxena
Below is the code where I'm facing issue. The data is being coming up in store as it is available to ComBox.. but not able to read data using each function or by other means? So is it that Data in store can only be fed to components? In another example I created a simplestore (ArrayStore) paased data manually using loadDATA().. there each function was working!!!
In below case to if I add one record after load using ADD(), each function would get executed one time showing data that I just added... and that just added data is not available to components!!! How come!!!
May be I'm missing some very basic concept as I'm still very new to EXT.
Would be really greatful for response.
var proxy = new Ext.data.ScriptTagProxy({
url: 'http://127.0.0.1:8500/extex/kebyid.cfm',
method: 'POST'
});
var rec = Ext.data.Record.create([
{name: 'EMPID', mapping: 1},
{name: 'KE', mapping: 2},
{name: 'SOLUTION', mapping: 3},
{name: 'ATTACH_KE', mapping: 4},
{name: 'ATTACH_SOLUTION', mapping: 5}
]);
var myReader = new Ext.data.ArrayReader({
idIndex: 0,
root: 'DATA'
}, rec);
var store = new Ext.data.ArrayStore({
proxy: new Ext.data.HttpProxy({
url: '/extex/kebyid.cfm',
method: 'POST'
}),
autoSave: true,
autoLoad: true,
root: 'DATA',
fields: [
{name: 'KEID', mapping: 0},
{name: 'EMPID', mapping: 1},
{name: 'KE', mapping: 2},
{name: 'SOLUTION', mapping: 3},
{name: 'ATTACH_KE', mapping: 4},
{name: 'ATTACH_SOLUTION', mapping: 5}
]
});
store.each(function(){
alert('!!!!'); //**************NOT WORKING
});
var catCB = new Ext.form.ComboBox({
fieldLabel: 'Category',
layout:'absolute',
x: 100,
y: 5,
store: store, //************* DATA IS THERE AS STORE IS PROVIDING DATA TO COMBOBOX
emptyText:'Select Category...',
valueField : 'KEID',
displayField : 'KE',
hiddenName : 'category',
hiddenvalue : 'None',
mode: 'local',
editable : false,
lastQuery: '',
renderTo: Ext.get("d1"),
listeners: {
'beforequery': function(qe){
qe.forceAll = true;
}}
});
First of all, you cannot use your server's output for scriptTagProxy. scriptTagProxy utilises JSONP technology. So output should look like this:
callback({
"COLUMNS":["KEDBID","EMPID","KE","SOLUTION","ATTACH_KE","ATTACH_SOLUTION"],
"DATA":[
[1,36661,"While adding a new user, if his\/her profile is missing, it could be LDAP server issue.","Contact Mr. ABC from infra team to get user's profile corrected on server","screenshots.jpg","conacts.doc"],
[2,36661,"The error code # 123445 is trivial that may occur at particular time.","To resolve this issue, we will need to ask DBA team to refresh database. That will fix this type of errors","NA","NA"]
]
});
Then simply use ArrayStore as your store. It uses ArrayReader by default:
var store = new Ext.data.ArrayStore({
proxy: new Ext.data.ScriptTagProxy({
url: 'http://example.com/get_data.php'
}),
root: 'DATA',
fields: [
'id',
// ...,
// ...,
// ...
]
});
UPDATE
I forgot that you are using 'DATA' as root property. Added it to store config.

.NET DateTime serialised to JSON for use in ExtJs JsonStore(event store for ExtJs Calendar)?

I'm trying to set up a Json Store for an ExtJs Calendar.
The store uses a Http Proxy to retrieve it's data.
The stores fields include startDate and endDate which are objects of type date.
I'm serializing data in my C# code into Json which will be requested by the Http proxy.
I am wondering should I serialize the start and endates as a string or as C# DateTime type.
At the moment I am serialising them as DateTime types.
The Json response looks like this:
{"Data":
"items":[{
"cid":"0",
"end":"\/Date(1275260400000+0100)\/",
"notes":"4:00",
"start":"\/Date(1275260400000+0100)\/",
"title":"Basic""}]
The start and end properties look like some sort of date reference.
I have tried serialising the startDate and endDate's as strings rather than DateTime types.
This returns the following JsonResponse:
{"Data":
"items":[{
"cid":"0",
"end":"03/06/10",
"notes":"4:00",
"start":"04/06/10",
"title":"Basic""}]
However, in both cases when the store has finished loading the endDate and startDate fields are undefined.
What should I do here?
I was thinking maybe i have to format the dates into a certain format expected by extjs?
Below is some sample code:
this.eventStore = new Ext.data.JsonStore({
id: 'eventStore',
root: 'Data.items',
proxy: new Ext.data.HttpProxy({
url: AppRootPath + 'Calendar/GetCalendarData',
method: 'POST'
}),//proxy
fields: Ext.calendar.EventRecord.prototype.fields.getRange()
});
Check the documentation for Ext.data.Field - http://dev.sencha.com/deploy/dev/docs/?class=Ext.data.Field . It has a property named 'dateFormat' that allows you to specify the exact date format.
I had the same problem and I solved it like this:
fields: [
{ name: 'Id', type: 'int' },
{ name: 'ResourceId', mapping: 'fitter_id', type: 'int' },
{ name: 'StartDate', type: 'date', format: 'd/m/Y G:i' },
{ name: 'EndDate', type: 'date', format: 'd/m/Y G:i' },
{ name: 'status', type: 'int' },
{ name: 'job_id', type: 'int' }
]

How to return a Date value from JSON to Google Visualization API

is there a way to retrieve date value from JSON in Google Visualization API?
Here is the snipplet for playground please copy the code below into it
When you run the code you won't have anything in result. you should remove the quotes from the date value I marked with comment in order to retrieve result.
function drawVisualization() {
var JSONObject = {
cols:
[
{id: 'header1', label: 'Header1', type: 'string'},
{id: 'header2', label: 'Header2', type: 'date'}
],
rows:
[
{
c:
[
{v: 'Value1'},
{v: "new Date(2010, 3, 28)"} // <= This is the format I receive from WebService
]
},
{
c:
[
{v: 'Value2'},
{v: new Date(2010, 3, 28)} // <=This is the format Google API accepts
]
}
]
};
var data = new google.visualization.DataTable(JSONObject, 0.5);
visualization = new google.visualization.Table(document.getElementById('table'));
visualization.draw(data, {'allowHtml': true});
}
I just ran into this problem myself, so I thought I'd paste the answer from the google api documentation, located here http://code.google.com/apis/chart/interactive/docs/dev/implementing_data_source.html#jsondatatable
"JSON does not support JavaScript Date values (for example, "new Date(2008,1,28,0,31,26)"; the API implementation does. However, the API does now support a custom valid JSON representation of dates as a string in the following format: Date(year, month, day[,hour, minute, second[, millisecond]]) where everything after day is optional, and months are zero-based."
I was running into same problem and above solution did not work. After searching for hours I found following post and the solution in there worked.
https://groups.google.com/forum/#!msg/google-visualization-api/SCDuNjuo7xo/ofAOTVbZg7YJ
Do not include "new" in the json string so it will be just:
v:"Date(2009, 9, 28)"
I suppose that the quote is not at the correct place in your snippet "new Date(2010, 3, 28")
Write instead "new Date(2010, 3, 28)"
Json format does not accept javascript object so the server return a string.
JSON knows only numbers, boolean constants, string, null, vector and 'object' (much more a dictionnary).
I suppose that you have to perform an eval() of the returned string (do not forget to check inputs).
Another alternative is to use a Regex to extract the fields something like /new Date\((\d+),(\d+),(\d+)\)/ will work.