JSON String and Object Conversion Example Analysis
- 2021-06-28 10:53:13
- OfStack
This paper gives an example of how JSON strings and objects convert to each other.Share it for your reference, as follows:
My colleague asked me a question - how do I access the values in the json object when the server side returns an json structured string?Has jquery parsed the returned JSON data?
I wrote a small demo myself, and I checked some information from the Internet, so I can share it with you here
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<script src="jquery-1.6.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(
function(){
var json = {"name":"Mike","sex":" female ","age":29};
alert(typeof json);
var temp = obj2str(json);
alert(temp);
alert(typeof temp);
}
);
// The following method is to add json Object to String
function obj2str(o){
var r = [];
if(typeof o =="string") return "\""+o.replace(/([\'\"\\])/g,"\\$1").replace(/(\n)/g,"\\n").replace(/(\r)/g,"\\r").replace(/(\t)/g,"\\t")+"\"";
if(typeof o =="undefined") return "undefined";
if(typeof o == "object"){
if(o===null) return "null";
else if(!o.sort){
for(var i in o)
r.push(i+":"+obj2str(o[i]))
r="{"+r.join()+"}"
}else{
for(var i =0;i<o.length;i++)
r.push(obj2str(o[i]))
r="["+r.join()+"]"
}
return r;
}
return o.toString();
}
/* Use jquery Plug-ins, note that json Of key-value Must all be strings, that is, they need to be wrapped in double quotes ,
You cannot use single quotation marks if value Is a number, you don't need to wrap it in double quotes */
function jquery_string_to_json(){
var jsonString = '{"name":"huangbiao","sex":"boy","age":16}';
//var jsonString = "{'name':'huangbiao','sex':'boy','age':16}";// Wrong declaration
alert(typeof jsonString);
var obj = jQuery.parseJSON(jsonString);
alert(typeof obj);
}
/* Use eval Method on the inside of a string key-value Must be enclosed in double quotation marks, not single quotation marks, otherwise no
Ability to parse normally */
function String_to_JSON(){
var json = '{"name":"huangbiao","sex":"boy","age":16}';
var temp = eval('('+json+')');//eval Method parentheses are required, otherwise script errors are reported
alert(typeof temp);
alert(temp.name);
// Use JSON Objects can only be in IE8 This conversion is not recommended because the above version supports it
//var json = '{"name":"Mike","sex":" female ","age":"29"}';
//var temp = JSON.parse(json);
//alert(temp.name);
}
</script>
<title> Untitled Document </title>
</head>
<body>
</body>
</html>
In your work, you find a string passed from the server end to the front end in JSON format, using eval ("("+json+"));There is no way to convert the resulting string to an JSON object, as follows:
function obj2str(o){
var r = [];
if(typeof o =="string") return "\""+o.replace(/([\'\"\\])/g,"\\$1").replace(/(\n)/g,"\\n").replace(/(\r)/g,"\\r").replace(/(\t)/g,"\\t")+"\"";
if(typeof o =="undefined") return "undefined";
if(typeof o == "object"){
if(o===null) return "null";
else if(!o.sort){
for(var i in o)
r.push(i+":"+obj2str(o[i]))
r="{"+r.join()+"}"
}else{
for(var i =0;i<o.length;i++)
r.push(obj2str(o[i]))
r="["+r.join()+"]"
}
return r;
}
return o.toString();
}
function json2obj(o){
var result = obj2str(o);
return eval("(" + result + ")");
}
Call the method json2obj (o).
PS: Here are a few more json online tools that you can use in future development:
Online JSON code validation, validation, beautification, formatting tools:
http://tools.ofstack.com/code/json
JSON Online Formatting Tool:
http://tools.ofstack.com/code/jsonformat
Online XML/JSON Interchange Tool:
http://tools.ofstack.com/code/xmljson
Online Format/Beautify/Compress/Edit/Convert Tool for json Code:
http://tools.ofstack.com/code/jsoncodeformat
C Language Style/HTML/CSS/json Code Formatting Beautification Tool:
http://tools.ofstack.com/code/ccode_html_css_json
More readers interested in JavaScript-related content can view this site's topics: json Operation Skills Summary in JavaScript, JavaScript Switching Special Effects and Skills Summary, JavaScript Find Algorithmic Skills Summary, JavaScript Animation Special Effects and Skills Summary, JavaScript Errors and Debugging Skills Summary, JavaScript Data Structure and Algorithmic Skills Summary,Summary of JavaScript Traversal Algorithms and Techniques and Summary of JavaScript Mathematical Operation Usage
I hope that the description in this paper will be helpful to everyone's JavaScript program design.