————————————————————————————————————
<script type= "Text/javascript" >
Create the data for the object based on the user's input
function Buildobj () {
Get new elements for the DOM of key and Val
var key = document.getElementById (' key '). Value;
var val = document.getElementById (' val '). Value;
Gets the contents of the current object text
var str = document.getElementById (' Obj_txt '). Innerhtml.trim ();
Convert a character to a JavaScript object
var obj = str== '? {}:eval (' (' +str+ ') ');
Use regular expressions, if the data is numeric, connect directly, otherwise you need to add single quotation marks
if (/\d+\.? \d*/.test (Val))
Obj[key] = val;
Else
Obj[key] = ' \ ' +val+ ' \ '; Add single quotes to Val
Print out the text of the latest object
document.getElementById (' Obj_txt '). InnerHTML = ConvertObj (obj);
}
Convert objects into textual form, which is also the form of JSON conversion
function ConvertObj (obj) {
var str = ' {'; Defines a character variable for concatenation
For (var prop in obj) {//properties of the convenience object
If it is an object type, the connection is traversed
if (typeof (Obj[prop]) = = = ' object ') {
str + = prop+ ': ' +convertobj (Obj[prop]) + ', ';
If it is in character form, you need to add single quotation marks
}else if (typeof (Obj[prop]) = = ' String ') {
str + = prop+ ': \ ' +obj[prop]+ ' \ ', ';
The others are displayed directly
}else{
str + = prop+ ': ' +obj[prop]+ ', ';
}
}
Remove the last comma, otherwise it is not a standard form
if (Str.charat (str.length-1) = = ', ') {
str = STR.SUBSTR (0,str.length-1);
}
str + = '} '; Stitching the last curly brace
return str; Returns the final stitching result character
}
</script>
————————————————————————————————————
The function of the convetobj () function is to convert data from character form to object form, which also uses recursive methods.
In this function, you need to first consider the type of data, the basic data type is only numeric and character type, the number type does not have to add single quotation marks, and the character type needs to add single quotation marks.
objects and arrays-converting data to Objects