想要将JSON数据导入我的本地存储

时间:2017-07-25 23:35:26

标签: json

我正在尝试将我的JSON数据存储到本地存储中。我无法找到办法。如果有人对此有任何疑问,请帮助我。这是我的JSON数据。 http://67.209.121.4/products.json 。任何帮助都非常感谢。谢谢!

2 个答案:

答案 0 :(得分: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文件中运行该代码才能运行。

答案 1 :(得分: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!");
        }); 
    }

})

在尝试在Node.js中执行此代码之前,请记住使用命令npm install fs && npm install request