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

标签 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>

最佳答案

简单地 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");

关于JavaScript——Json 字符串到对象的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40733025/

相关文章:

javascript - Jquery 提交处理程序有两个按钮?

javascript - 带有发布数据的请求后,PHP 中的 $_POST 数组为空

JavaScript - 构建 JSON 对象

javascript - 根据屏幕尺寸更改 href 的一个 'attribute'

java - 使用 JAX-RS 作为 GET 方法返回的接口(interface)

c# - Azure 移动服务计划作业 - 是否有使用 javascript 的替代方案?

javascript - 如何根据日期属性之间的范围是否包含给定日期来过滤对象数组?

ios - 你如何在 swift 中从 JSON 中排序 NSMutableArray?

ruby - 如何将此哈希组合到单个 JSON 对象?

java - JSON 对象表示