简体   繁体   中英

How can I convert JSON format file to JSON object?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM