简体   繁体   English

JavaScript — Json字符串到对象的转换

[英]JavaScript — Json String to Object conversion

The following is my code for converting Json string to object. 以下是我的代码,用于将Json字符串转换为对象。 Please suggest me any better and more reliable way. 请给我建议任何更好,更可靠的方法。

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"
    import="com.pks.UserBean"
    %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<title>Insert title here</title>
</head>
<body>
    This page contains data
            <% 
            UserBean bean = (UserBean)(session.getAttribute("currentSessionUser"));
            %>
            s<h1><%String a = bean.getUserName(); %></h1>
            <%= a %>

            <script type="text/javascript">
            alert("hELLO WORLD");
            var my = '<%= a %>'
            alert(my);

            var obj = jQuery.parseJSON('{"name":"John"}');
            alert( obj.name === "John" );

            </script>

</body>
</html>

Simply JSON.parse() method would suffice your requirement, no need of jQuery at all. 只需JSON.parse()方法就可以满足您的要求,完全不需要jQuery。

 var jsonString = '{ "name" : "John" }'; var jsonObject = JSON.parse(jsonString); console.log(jsonObject); // The example you tried on your code. alert(jsonObject.name === "John"); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM