我在一个使用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"
}];

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


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

var arr_from_json = JSON.parse( json_string );

在不支持json2的浏览器中,可以包含json2库。

JSON的全部意义在于JSON字符串可以不做任何事情就转换为本机对象。检查这个链接

你可以使用eval(字符串)或JSON.parse(字符串)。

但是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.

像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);

这样你就不需要任何外部库,而且它仍然可以在旧的浏览器上运行。

如果你在服务器端将字符串粘贴到html中,不需要做任何事情:

对于jsp中的纯java:

var jsonObj=<%=jsonStringInJavaServlet%>;

对于jsp宽度struts:

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

收集数组中的所有项并返回一个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;
    },

为了解析相同的数据,我们这样做

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)
            });
        });

}

如果您还希望反序列化对象具有函数,您可以使用我的小工具: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());

我认为这应该有所帮助:

另外,文档也证明了你可以对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.

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

好并且有效

var yourJsonObject = JSON.parse(json_as_text);

我看不出你为什么更喜欢用eval。这只会使您的应用程序处于危险之中。

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

不好——但也有用

var yourJsonObject = eval(json_as_text);

为什么eval是一个坏主意?

考虑下面的例子。

某些第三方或用户提供了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"
}]
`;

服务器端脚本处理这些数据。

使用JSON.parse:

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

将把:

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

函数将不会被执行。

你是安全的。

使用eval ():

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

将执行函数并返回文本。

如果你在服务器端运行这个,我将这个无害的函数替换为一个,从你的网站文件夹中删除文件或做一些有害的事情,那么你的应用程序将被黑客入侵。在本例中不会抛出错误/警告。

你不安全。

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

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

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