I use a dojo request.get to read a txt file in JSON format, but can't convert it to JSON object.
The "datagrid.txt" stored some data as:
[
{"col1":"val1", "col2":"val2", "col3":"val3"},
{"col1":"val1", "col2":"val2", "col3":"val3"},
{"col1":"val1", "col2":"val2", "col3":"val3"}
]
The requesting client code is as:
require(['dojo/_base/lang', 'dojox/grid/DataGrid', 'dojo/data/ItemFileWriteStore', 'dojo/dom', 'dojo/request', 'dojo/domReady!'],
function(lang, DataGrid, ItemFileWriteStore, dom, request){
request.get("datagrid.txt",{
// Parse data from JSON to a JavaScript object
handleAs: "json"
}
).then(
function(text){
var datalist = JSON.stringify(text);
for(var i = 0, l = 16; i < l; i++){
console.log( datalist[i] );
}
});
The console.log displays things in string(such as "[","{"), not what as I expected an array({"col1":"val1", "col2":"val2", "col3":"val3"}), which I could used to populate a dojo datagrid data store.
Dojo can handle the JSON format on its own. Official docs
I think your Problem lies in the way you're writing your datagrid.txt and the style you try to read the data later.
Here's my solution:
require(['dojo/_base/lang', 'dojox/grid/DataGrid', 'dojo/data/ItemFileWriteStore',
'dojo/dom', 'dojo/request', 'dojo/domReady!'],
function(lang, DataGrid, ItemFileWriteStore, dom, request){
request.get("datagrid.txt",{
// Parse data from JSON to a JavaScript object
handleAs: "json"
}
).then(
function(text){
var datalist = [];
dojo.forEach(text,function(thisText,i){
//add each single Object from the datagrid.txt to datagrid-array
datalist.push(thisText);
//alert the newly added item in datagrid
console.log(datalist);
});
});
I think this should fix your Problem.
Regards, Miriam
Related
I would like to extract a CSV local file in PHP using AJAX.
To do that I tried to use Papa Parse and it works great. The problem is to pass the results with AJAX. I tried with JSON.stringify, I tried to pass only the first field; I tried also to create a JSON object and then add the results to this object but, I don't know why, when I extract in PHP I got only the values of the original object.
values = {};
values['row_1'] = 'value1';
values['row_2'] = 'value2';
i = 3
$("input[type=file]").parse({
config: {
delimiter: ",",
step: function(results) {
value = results.data[0]
values['row_' + i] = value
i = i + 1
}
}
});
$.ajax({
type: "POST",
url: "extract-csv.php",
data: {
id: $('#id').val(),
...
values: values
}
...
})
With this code on PHP I returned only "value1" and "value2" (if I print "values" in the console I get object with 2++ elements)
Papa Parse worked after Ajax, so the solution is to put the Ajax call in the "Complete" Papa Parse function and then everything works fine!
I've the below combination of server-side and client-side json processing code. I'm able to load json data from remote url and from local .js file.
But, somehow I'm unable to figure out how to load data from the serverjson object in the below code snippet.
var json ;
<#list jsons as json>
serverjson = ${json};
console.log(serverjson);
$.getJSON(---have to load data from json object----).done(function (jsonData) {
var time = 0; var curc = 0; var prec = 0;
$.each(jsonData.current.timeSeries, function(i,item){
//console.log(jsonData.current.timeSeries[i].beginTimeSeconds+" : "+jsonData.current.timeSeries[i].endTimeSeconds+" : "+jsonData.current.timeSeries[i].inspectedCount);
time = jsonData.current.timeSeries[i].beginTimeSeconds;
curc = jsonData.current.timeSeries[i].inspectedCount;
//curdata.addRows([curc]);
curdata.push(curc)
//data.addRows([[jsonData.current.timeSeries[i].beginTimeSeconds,jsonData.current.timeSeries[i].endTimeSeconds,jsonData.current.timeSeries[i].inspectedCount]]);
});
</#list>
So, to conclude, I'm not passing remote url or .js file in the $.getJSON() function, I need to pass serverjson object.
Please help me how to solve this.
Thanks in advance.
Instead of:
$.getJSON(---have to load data from json object----).done(function (jsonData) {
// code
});
do:
var jsonData = JSON.parse(serverjson);
// code
I am confused because I have two functions, one using ajax to get the data and the other getting it from a string.
function loadMenuData() {
$.ajax({
url: "./shoulders.json",
success: function(data) {
dataObj = $.parseJSON(data);
$.each(dataObj, function( key, value) {
$(document).find("#dropDownDest").append($('<option></option>').val(value.id).html(value.name));
});
}
});
}
function loadMenuDataX() {
var str = '[{"id":"A","name":"Bart"},{"id":"B", "name":"Joe"},{"id":"C", "name":"Gomer"}]';
dataObj = $.parseJSON(str);
$.each(dataObj, function( key, value) {
$(document).find("#dropDownDest").append($('<option></option>').val(value.id).html(value.name));
});
}
I created the file shoulders.json buy pasting the str between the single quotes ' into the file. If I call loadMenuX, it fills in the <select></select> correctly. If I call loadMenu, it doesn't fill anything in.
I have tried JSON.parse instead of the above and get the same behavior.
I was unable to use $("#dropDownDest") and had to use $(document).find. Why?
Hitting the DOM each loop seems to be excessive. What would be a better way to do the ajax version THAT WOULD WORK and be better?
What would be a better way to do the ajax version THAT WOULD WORK and be better?
Because you're trying to get JSON file the better way is using jQuery.getJSON(), so you will be sure that the returned result is in json format :
$.getJSON( "./shoulders.json", function( json ) {
$.each(json, function( key, value) {
$("#dropDownDest").append('<option value="+value.id+">'+value.name+'</option>');
});
});
Hope this helps.
I'm trying to use a JSON api and retrieve some data. I'm still new to it though and I can't seem to figure out which value to use. My JSON API looks something like this:
[
{"lang":"english","visual":"<span>Text</span>","weight":0.92},
{"lang":"swedish","visual":"<span>Text</span>","weight":0.22},
//etc
]
and my jQuery is:
$.getJSON(url ,function(data) {
$.each(data.lang, function(i, item) {
dataName = item["visual"];
console.log(dataName);
});
});
but nothing is being logged. How do I navigate through a JSON tree? Thanks
data.lang is undefined. lang is a property of each object in the array of objects that data holds. Simply iterate the data array, each object will contain the visual property (as well as lang);
$.getJSON(url ,function(data) {
$.each(data, function() {
var lang = this["lang"];
var dataName = this["visual"];
console.log(dataName);
});
});
I am a beginner in Javascript. I hope to get some help.
I built a local server using MAMP, and all my files are local. I want to read a value from a json file. This json file(data.json) has only one item {"type":2}, and I only want to use the value(2 in this case). But the value of "type" changes, so Javascript should read it constantly and maybe save it into a var in Javascript.
Can I listen for changes to that file so that I can be sure I always have the most up to date value for type?
I am still not familiar with Javascript. I would really appreciate it if you could give me some specific codes or examples.
//Either
var json = {test:"test"};
console.log(json);
//Access JSON
console.log(json.test);
//Or
$.getJSON( "test.json", function( data ) {
//Assign the json to your JSON variable
json = data;
});
console.log(json);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
JSON can come from anywhere, inbuilt into jquery is parseJSON which will return the json input string as a javascript object.
http://api.jquery.com/jquery.parsejson/
var obj = $.parseJSON( '{ "name": "John" }' );
alert( obj.name === "John" );
where the json can come from anywhere.. an ajax call or where ever else.
$.ajax({
url:'some url',
data: someobject,
type: 'get',
success: function( responseFromServer ){
var obj = $.parseJSON( responseFromServer );
alert( obj.name === "John" );
}
});