我在一个使用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对象(或数组)?或者我必须手动分割字符串并手动构建我的对象?


当前回答

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

对于jsp中的纯java:

var jsonObj=<%=jsonStringInJavaServlet%>;

对于jsp宽度struts:

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

其他回答

现代浏览器支持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.

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

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

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

我认为这应该有所帮助:

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