Cordova readAsText returns a json string that cannot be parsed for a JSON object

I read my json file using readAsText functions with http and cordova.

The http request returns an object that is in order.

The cordova file readAsText returns a string containing the optional characters "r \ n \". This makes it impossible to use JSON.parse (evt.target.result)

function readJson(absPath, success, failed){
        window.resolveLocalFileSystemURL(absPath, function (entry) {
            entry.file(function (file) {
                var reader = new FileReader();
                reader.onloadend = function (evt) {
                    success(evt.target.result);
                };
                reader.readAsText(file);
            }, failed);
        }, failed);
}

readJson(cordova.file.dataDirectory + 'my.json', function(res){
    console.log(JSON.parse(res));  //here I've got an parsing error due to presence of r\n\ symbols
}, failed );

How to read JSON files using cordova?

UPDATE:

The funny thing is that the following works:

a = '{\r\n"a":"1",\r\n"b":"2"\r\n}';
b = JSON.parse(a);

so the problem is not only with \ r \ n ... there is something else added by cordova readAsText

UPDATE2

as the workaround I'm using now var object = eval("(" + res + ")")

Keep looking for a general way to load json objects ...

+4
source share
2

, , .

readAsText , , RegExp . :

 var sanitizerRegex = new RegExp(String.fromCharCode(10), 'g');
 var sanitizedData = JSON.parse(result.replace(sanitizerRegex, ''));

String fromCharCode, , "g" - . , "n", , "\n".

, JSON.parse , .

, eval, , , , JSON . cordova eval .

+2

. readAsText .

:

{ "name": "John" } = > ? { "name": "John" } (?: API ?, )

, substr (1) JSON.

fileContent = fileContent.substr(1);
var jData = jQuery.parseJSON(fileContent);
0

All Articles