将 JSON 反序列化为 JavaScript 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6487167/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:59:51  来源:igfitidea点击:

Deserializing a JSON into a JavaScript object

javascriptjsondeserialization

提问by mj_

I have a string in a Java server application that is accessed using AJAX. It looks something like the following:

我在使用 AJAX 访问的 Java 服务器应用程序中有一个字符串。它看起来像下面这样:

var json = [{
    "adjacencies": [
        {
          "nodeTo": "graphnode2",
          "nodeFrom": "graphnode1",
          "data": {
            "$color": "#557EAA"
          }
        }
    ],
    "data": {
      "$color": "#EBB056",
      "$type": "triangle",
      "$dim": 9
    },
    "id": "graphnode1",
    "name": "graphnode1"
},{
    "adjacencies": [],
    "data": {
      "$color": "#EBB056",
      "$type": "triangle",
      "$dim": 9
    },
    "id": "graphnode2",
    "name": "graphnode2"
}];

When the string gets pulled from the server, is there an easy way to turn this into a living JavaScript object (or array)? Or do I have to manually split the string and build my object manually?

当字符串从服务器中取出时,是否有一种简单的方法可以将其转换为活的 JavaScript 对象(或数组)?还是我必须手动拆分字符串并手动构建我的对象?

回答by user113716

Modern browsers support JSON.parse().

现代浏览器支持JSON.parse().

var arr_from_json = JSON.parse( json_string );

In browsers that don't, you can include the json2library.

在不浏览器,您可以包括json2库中

回答by Abhinav

The whole point of JSON is that JSON strings can be converted to native objects without doing anything. Check this link

JSON 的全部意义在于可以将 JSON 字符串转换为本地对象,而无需执行任何操作。检查此链接

You can use either eval(string)or JSON.parse(string).

您可以使用eval(string)JSON.parse(string)

However, evalis risky. From json.org:

不过,eval是有风险的。来自 json.org:

The eval function is very fast. However, it can compile and execute any JavaScript program, so there can be security issues. The use of eval is indicated when the source is trusted and competent. It is much safer to use a JSON parser. In web applications over XMLHttpRequest, communication is permitted only to the same origin that provide that page, so it is trusted. But it might not be competent. If the server is not rigorous in its JSON encoding, or if it does not scrupulously validate all of its inputs, then it could deliver invalid JSON text that could be carrying dangerous script. The eval function would execute the script, unleashing its malice.

eval 函数非常快。但是,它可以编译和执行任何 JavaScript 程序,因此可能存在安全问题。当来源可信且有能力时,表明使用 eval。使用 JSON 解析器要安全得多。在通过 XMLHttpRequest 的 Web 应用程序中,只允许与提供该页面的同一来源进行通信,因此它是可信的。但它可能无法胜任。如果服务器的 JSON 编码不严格,或者它没有严格验证所有输入,那么它可能会传递可能携带危险脚本的无效 JSON 文本。eval 函数将执行脚本,释放其恶意。

回答by Ravan Scafi

Do like jQuery does! (the essence)

像 jQuery 那样做!(精华)

function parseJSON(data) {
    return window.JSON && window.JSON.parse ? window.JSON.parse( data ) : (new Function("return " + data))(); 
}
// testing
obj = parseJSON('{"name":"John"}');
alert(obj.name);

This way you don't need any external library and it still works on old browsers.

这样你就不需要任何外部库,它仍然适用于旧浏览器。

回答by Tarun Gupta

TO collect all item of an array and return a json object

收集数组的所有项并返回一个 json 对象

collectData: function (arrayElements) {

        var main = [];

        for (var i = 0; i < arrayElements.length; i++) {
            var data = {};
            this.e = arrayElements[i];            
            data.text = arrayElements[i].text;
            data.val = arrayElements[i].value;
            main[i] = data;
        }
        return main;
    },

TO parse the same data we go through like this

解析我们这样经历的相同数据

dummyParse: function (json) {       
        var o = JSON.parse(json); //conerted the string into JSON object        
        $.each(o, function () {
            inner = this;
            $.each(inner, function (index) {
                alert(this.text)
            });
        });

}

回答by DevWL

You could also use eval()but JSON.parse()is safer and easier way, so why would you?

您也可以使用eval()JSON.parse()更安全、更简单的方法,那为什么要使用呢?

good and works

好用

var yourJsonObject = JSON.parse(json_as_text);

I don't see any reason why would you prefer to use eval. It only puts your application at risk.

我看不出有什么理由让您更喜欢使用eval. 它只会使您的应用程序处于危险之中。

That said - this isalso possible.

这就是说-这也是可能的。

bad - but also works

坏 - 但也有效

var yourJsonObject = eval(json_as_text);

Why is evala bad idea?

为什么是eval坏主意?

Consider the following example.

考虑以下示例。

Some third party or user provided JSON string data.

某些第三方或用户提供了 JSON 字符串数据。

var json = `
[{
    "adjacencies": [
        {
          "nodeTo": function(){
            return "delete server files - you have been hacked!";
          }(),
          "nodeFrom": "graphnode1",
          "data": {
            "$color": "#557EAA"
          }
        }
    ],
    "data": {
      "$color": "#EBB056",
      "$type": "triangle",
      "$dim": 9
    },
    "id": "graphnode1",
    "name": "graphnode1"
},{
    "adjacencies": [],
    "data": {
      "$color": "#EBB056",
      "$type": "triangle",
      "$dim": 9
    },
    "id": "graphnode2",
    "name": "graphnode2"
}]
`;

Your server-side script processes that data.

您的服务器端脚本处理该数据。

Using JSON.parse:

使用JSON.parse

window.onload = function(){
  var placeholder = document.getElementById('placeholder1');
  placeholder.innerHTML = JSON.parse(json)[0].adjacencies[0].nodeTo;
}

will throw:

会抛出:

Uncaught SyntaxError: Unexpected token u in JSON at position X. 

Function will not get executed.

函数不会被执行。

You are safe.

你很安全。

Using eval():

使用eval()

window.onload = function(){
  var placeholder = document.getElementById('placeholder1');
  placeholder.innerHTML = eval(json)[0].adjacencies[0].nodeTo;
}

will execute the function and return the text.

将执行函数并返回文本。

If I replace that harmless function with one that removes files from your website folder you have been hacked. No errors/warnings will get thrown in this example.

如果我将那个无害的功能替换为从您的网站文件夹中删除文件的功能,那么您已经被黑客入侵了。在这个例子中不会抛出任何错误/警告。

You are NOT safe.

你不安全。

I was able to manipulate a JSON text string so it acts as a function which will execute on the server.

我能够操作 JSON 文本字符串,因此它充当将在服务器上执行的函数。

eval(JSON)[0].adjacencies[0].nodeToexpects to process a JSON string but, in reality, we just executed a function on our server.

eval(JSON)[0].adjacencies[0].nodeTo期望处理一个 JSON 字符串,但实际上,我们只是在我们的服务器上执行了一个函数。

This could also be prevented if we server-side check all user-provided data before passing it to an eval()function but why not just use the built-in tool for parsing JSON and avoid all this trouble and danger?

如果我们在将用户提供的所有数据传递给eval()函数之前检查所有用户提供的数据,也可以防止这种情况发生,但为什么不使用内置工具来解析 JSON 并避免所有这些麻烦和危险呢?

回答by fishgen

And if you also want the deserialised object to have functions, you could use my small tool: https://github.com/khayll/jsmix

如果您还希望反序列化的对象具有功能,则可以使用我的小工具:https: //github.com/khayll/jsmix

//first you'll need to define your model
var GraphNode = function() {};
GraphNode.prototype.getType = function() {
   return this.$type;
}

var Adjacency = function() {};
Adjacency.prototype.getData =n function() {
    return this.data;
}

//then you could say:
var result = JSMix(jsonData)
    .withObject(GraphNode.prototype, "*")
    .withObject(Adjacency.prototype, "*.adjacencies")
    .build();

//and use them
console.log(result[1][0].getData());

回答by surfealokesea

If you paste the string in server-side into the html don't need to do nothing:

如果您将服务器端的字符串粘贴到 html 中,则无需执行任何操作:

For plain java in jsp:

对于jsp中的纯java:

var jsonObj=<%=jsonStringInJavaServlet%>;

For jsp width struts:

对于jsp宽度支柱:

var jsonObj=<s:property value="jsonStringInJavaServlet" escape="false" escapeHtml="false"/>;

回答by PSXGamerPro1

I think this should help:

我认为这应该有帮助:

Also documentations also prove that you can use require() for json files: https://www.bennadel.com/blog/2908-you-can-use-require-to-load-json-javascript-object-notation-files-in-node-js.htm

此外,文档还证明您可以对 json 文件使用 require():https: //www.bennadel.com/blog/2908-you-can-use-require-to-load-json-javascript-object-notation-files -in-node-js.htm

var jsonfile = require("./path/to/jsonfile.json");
node = jsonfile.adjacencies.nodeTo;
node2 = jsonfile.adjacencies.nodeFrom;
node3 = jsonfile.adjacencies.data.$color;
//other things.