JavaScript - Json String to Object转换

时间:2016-11-22 02:51:52

标签: javascript json

以下是我将Json字符串转换为对象的代码。请建议我任何更好,更可靠的方式。

<%@ 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>

1 个答案:

答案 0 :(得分:-1)

简单JSON.parse()方法就足以满足您的要求,完全不需要jQuery。

&#13;
&#13;
var jsonString = '{ "name" : "John" }';

var jsonObject = JSON.parse(jsonString);

console.log(jsonObject);

// The example you tried on your code.
alert(jsonObject.name === "John");
&#13;
&#13;
&#13;