[英]How to store a JSON file into a variable using Javascript native
我一直在嘗試將JSON文件中的數據存儲到Javascript中的變量中,直到JSON.parse函數不起作用為止,一切都很好。
我的文件稱為test.json,它看起來像這樣:
{
test: 'Hello World!'
}
我也嘗試將其更改為:
{ test: 'Hello World' }
我的JavaScript代碼是這樣的:
var a = OwNet.get( 'core/config/test.json', function( Res ) {
// Res is the response from an AJAX request (where i requested the test.json file)
if( Res !== "" && Res !== undefined && Res !== null ) {
// Here i tried to replace the line breaks, carriage returns and spaces. It failed.
// (I also tried to remove it)
Res.replace( /\r\n|\r|\n|\s*/gm, "" );
// Here i tried to transform Res in an object
tmp = JSON.stringify( Res );
return JSON.parse( tmp ); // This returns a string instead an object
} else return null;
});
唯一的問題是變量“ a”不是對象,而是一個字符串,我一直在尋找答案,但我一直沒有。
您的JSON無效,請更改為
{
"test": "HelloWorld!"
}
非常感謝大家,答案比我容易:
文件test.json:
{
"test": "Hello World!"
}
和代碼:
var a = OwNet.get( 'core/config/test.json', function( Res ) {
// Res is the response from an AJAX request (where i requested the test.json file)
if( Res !== "" && Res !== undefined && Res !== null ) {
// Replacing the line breaks, carriage returns and spaces
Res = Res.replace( /\r\n|\r|\n|\s*/gm, "" );
// Erased the JSON.stringify and replaced tmp by Res
return JSON.parse( Res );
} else return null;
});
{ "test": "Hello World!" }
{ "test": "Hello World!" }
,測試是一個字符串,需要像這樣顯示。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.