2017-07-25 42 views
0

我想將我的JSON數據存儲到本地存儲中。我無法找到辦法。如果任何人有任何想法,請協助我。這是我的JSON數據。 http://67.209.121.4/products.json。任何幫助非常感謝。提前感謝!想要將JSON數據導入到本地存儲

+0

https://serverfault.com/questions/707761/is-there-a-way-to-get-curl-output-into-a-file – Jacob

+0

@Jacob我想你是告訴他他的帖子是關閉的 - 而是你可以幫助他寫出更好的問題。這會更有幫助。我不想冒犯你。但是你是對的,因爲缺少細節,這是無關緊要的。 – sascha10000

回答

0

據我所知localStorage只存儲鍵/值對。因此,首先將JSON串化並存儲。要閱讀它,你需要得到字符串,然後解析它。見代碼:

var jn = { 
 
     "test": { 
 
      "test": 1, 
 
      "testx": 2, 
 
      "xtest": { 
 
       "x": 1, 
 
       "y": 2 
 
      }, 
 
      "test2": 1 
 
     }, 
 
     "xx":{ 
 
      "x":2, 
 
      "y": 3, 
 
      "z": [1,2,3] 
 
     } 
 
    }; 
 

 
    localStorage.setItem("myData", JSON.stringify(jn)); 
 
    var data = JSON.parse(localStorage.getItem("myData")); 
 
    console.log(data);

你需要運行一個HTML文件裏的代碼運行,因爲沙盒。

+0

如何使用javascript來完成上述文件http://67.209.121.4/products.json?任何幫助,高度讚賞。謝謝 – Rajesh

+0

你應該把拼圖部件放在一起並解決它。提供的和合並的答案都是解決方案。看起來你想讓其他人解決你的問題,但那不是什麼stackoverflow是。這是爲了幫助有具體問題的人解放思想或學習。 – sascha10000

0

如果您打算使用Node.js來完成此任務,您可能需要查看npm上的requestfs模塊。

除此之外,這段代碼也應約你正在尋找:

var request = require("request") 
var fs = require("fs") 

// This is your URL 
var url = "http://67.209.121.4/products.json" 

// This is the code for accessing and storing the data using request 
request({ 
    url: url, 
    json: true 
}, function (error, response, body) { 

    // This is the part where you store your data locally using fs 
    if (!error && response.statusCode === 200) { 
     var content = JSON.stringify(body); 
     fs.writeFile("./content.json", content, 'utf8', function (err) { 
      if (err) { 
       return console.log(err); 
      } 

      console.log("The file was saved!"); 
     }); 
    } 

}) 

記住使用命令npm install fs && npm install request您嘗試執行在Node.js的此代碼之前

+0

謝謝你的代碼。但是,我怎樣才能通過使用JavaScript代碼來做到這一點。非常感謝您的幫助。謝謝 – Rajesh

+0

純JavaScript解決方案。如果你知道JavaScript並且你能夠理解它:https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started – sascha10000

相關問題