在Javascript对象中用分号替换相等

时间:2014-08-05 19:28:43

标签: java javascript jquery jsp

我将来自servlet的Map<String,String>对象发送到密钥为attribute name且值为jsonvalue的jsp。我的要求是在这里收集root变量中的key值。但是当我尝试将这些地图对象分配给JavaScript变量时,由于地图对象在数据中包含=运算符,因此抛出错误。因此,要删除我为= :手动分配的错误,其工作正常。

那么请告诉我如何使用JavaScript代码删除带有=的{​​{1}}?或者有没有办法从servlet发送带分号的数据?

数据采用以下格式:

:

我正在尝试迭代此地图正常工作,如果:是否获得密钥。

var trees=   {dage={"nodeId":3,"value":"0-7","children":[{"nodeId":2,"value":"4-7","children":[{"nodeId":1,"value":"6-7","children":[{"nodeId":0,"value":"7","children":[]},{"nodeId":4,"value":"6","children":[]}]},{"nodeId":6,"value":"4-5","children":[{"nodeId":5,"value":"5","children":[]},{"nodeId":7,"value":"4","children":[]}]}]},{"nodeId":10,"value":"0-3","children":[{"nodeId":9,"value":"2-3","children":[{"nodeId":8,"value":"3","children":[]},{"nodeId":11,"value":"2","children":[]}]},{"nodeId":13,"value":"0-1","children":[{"nodeId":12,"value":"1","children":[]},{"nodeId":14,"value":"0","children":[]}]}]}]}, 

dpob={"nodeId":6,"value":"4;3;5;6;1;2;0","children":[{"nodeId":5,"value":"0","children":[{"nodeId":4,"value":"0","children":[{"nodeId":3,"value":"0","children":[{"nodeId":2,"value":"0","children":[{"nodeId":1,"value":"0","children":[{"nodeId":0,"value":"0","children":[]}]}]}]}]}]},{"nodeId":12,"value":"4;3;5;6;1;2","children":[{"nodeId":11,"value":"3;5;6;1;2","children":[{"nodeId":10,"value":"5;6;1;2","children":[{"nodeId":9,"value":"2","children":[{"nodeId":8,"value":"2","children":[{"nodeId":7,"value":"2","children":[]}]}]},{"nodeId":15,"value":"5;6;1","children":[{"nodeId":14,"value":"1","children":[{"nodeId":13,"value":"1","children":[]}]},{"nodeId":17,"value":"5;6","children":[{"nodeId":16,"value":"6","children":[]},{"nodeId":18,"value":"5","children":[]}]}]}]},{"nodeId":22,"value":"3","children":[{"nodeId":21,"value":"3","children":[{"nodeId":20,"value":"3","children":[{"nodeId":19,"value":"3","children":[]}]}]}]}]},{"nodeId":27,"value":"4","children":[{"nodeId":26,"value":"4","children":[{"nodeId":25,"value":"4","children":[{"nodeId":24,"value":"4","children":[{"nodeId":23,"value":"4","children":[]}]}]}]}]}]}]}}

这是我获取数据的jsp代码

for (var key in trees){
    if(key===attribute_name){
        root=trees[key];
        break;
    }
}

1 个答案:

答案 0 :(得分:0)

使用JSON解析库将Map<String, String>转换为JSON字符串。然后,将此数据设置为JavaScript代码中的变量(正确解析后)。

这是使用杰克逊图书馆的一个例子。

Java servlet(或您使用的任何控制器)代码:

Map<String, String> yourMap = ...;
//fill your map...
request.setAttribute("theMapAsJSON", new ObjectMapper().writeValueAsString(yourMap));

JavaScript代码:

<script type="text/javascript">
    var treeStructure = JSON.parse('${theMapAsJSON}'); //naive approach
<script>