Sample code for converting json strings to each other

  • 2020-03-30 03:44:32
  • OfStack

While the eval() function converts a JSON string to an object, the stringifier function does the opposite of parse and converts a js object to JSON text


<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 
<% 
String path = request.getContextPath(); 
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 
%> 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html> 
<head> 
<base href="<%=basePath%>" rel="external nofollow" > 
<title>My JSP 'test5.jsp' starting page</title> 
<meta http-equiv="pragma" content="no-cache"> 
<meta http-equiv="cache-control" content="no-cache"> 
<meta http-equiv="expires" content="0"> 
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 
<meta http-equiv="description" content="This is my page"> 
<!-- 
<link rel="stylesheet" type="text/css" href="styles.css" rel="external nofollow" > 
--> 
<script type="text/javascript" src="<%=basePath%>/js/json2.js"></script> 
<script type="text/javascript"> 
alert("xxxx"); 
var t="{'firstName': 'cyra', 'lastName': 'richardson', 'address': {"+ 
"'streetAddress': '1 Microsoft way', 'city': 'Redmond', 'state': 'WA',"+ 
"'postalCode': 98052 },'phoneNumbers': [ '425-777-7777','206-777-7777' ] }"; 
var jsonobj=eval('('+t+')'); 
alert(t.firstName+" xxx"); 
alert(jsonobj.lastName); 

var t2="[{name:'zhangsan',age:'24'},{name:'lisi',age:'30'},{name:'wangwu',age:'16'},{name:'tianqi',age:'7'}] "; 
var myobj=eval(t2); 
for(var i=0;i<myobj.length;i++){ 
alert(myobj[i].name); 
alert(myobj[i].age); 
} 

var t3="[['<a href=# onclick=openLink(14113295100, She qi county tax bureau bridgehead tax office ,14113295100,d6d223892dc94f5bb501d4408a68333d,swjg_dm);>14113295100</a>',' She qi county tax bureau bridgehead tax office ',' Sheqi county suburban township changjiang road west section ']]"; 
//The eval() function converts JSON strings into objects
var obj = eval(t3); 
for(var i=0;i<obj.length;i++){ 
for(var j=0;j<obj[i].length;j++){ 
alert(obj[i][j]); 
} 
var jsonText = JSON.stringify(obj); 
alert(jsonText); 
} 

/* 
//The stringifier function does the opposite of parse and converts a js object to JSON text.
var jsonText = JSON.stringify(obj); 
alert(jsonText); 

//For security reasons, it is best to use a JSON parser. A JSON parser will only accept JSON text. So it's safer.
var myObject = JSON.parse(myJSONtext, filter); 
//The optional filter parameter traverses each value key value pair and does the associated processing. Such as:
// Such as  
myData = JSON.parse(text, function (key, value) { 

return key.indexOf('date') >= 0 ? new Date(value) : value; }); 

//The stringifier function does the opposite of parse and converts a js object to JSON text.
var myJSONText = JSON.stringifier(myObject); 
*/ 
</SCRIPT> 

</head> 
<body> 
This is my JSP page. <br> 
</body> 
</html>

Related articles: