2017-07-25 65 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

相关问题