关于json的笔记,写得有点乱,下次有时间我再整理一下。
var
myFirstJSON
=
...
{
"firstName" : "John",
"lastName" : "Doe",
"age" : 23
}
;
document.writeln(myFirstJSON.firstName);
//
Outputs John
document.writeln(myFirstJSON.lastName);
//
Outputs Doe
document.writeln(myFirstJSON.age);
//
Outputs 23
基于java的json对象生成实现类:http://json.org/java/
JSONObject jsonObj
=
new
JSONObject();
jsonObj.put(
"
name
"
,
"
吉田
"
);
JSONArray dep
=
new
JSONArray();
dep.put(
"
管理部
"
);
dep.put(
"
開発部
"
);
dep.put(
"
営業部
"
);
jsonObj.put(
"
sex
"
,
"
M
"
);
jsonObj.putOpt(
"
department
"
, dep);
jsonObj.put(
"
age
"
,
23
);
setJson_xml(jsonObj.toString());
等价于json对象: {"sex":"M","age":23,"name":"吉田","department":["管理部","開発部","営業部"]}
需要一个json的解析类:json-parser.js (注:网上有个叫json.js的开源包,好像具有相同的功能)
(function ($) {
var m = {
'/b': '//b',
'/t': '//t',
'/n': '//n',
'/f': '//f',
'/r': '//r',
'"' : '//"',
'//': '////'
},
s = {
'array': function (x) {
var a = ['['], b, f, i, l = x.length, v;
for (i = 0; i < l; i += 1) {
v = x[i];
f = s[typeof v];
if (f) {
v = f(v);
if (typeof v == 'string') {
if (b) {
a[a.length] = ',';
}
a[a.length] = v;
b = true;
}
}
}
a[a.length] = ']';
return a.join('');
},
'boolean': function (x) {
return String(x);
},
'null': function (x) {
return "null";
},
'number': function (x) {
return isFinite(x) ? '"' + String(x) + '"' : 'null';
},
'object': function (x) {
if (x) {
if (typeof x.splice == "function") {
return s.array(x);
}
if (!isNaN(x)) {
return s.number(x);
}
var a = ['{'], b, f, i, v;
for (i in x) {
v = x[i];
f = s[typeof v];
if (f) {
v = f(v);
if (typeof v == 'string') {
if (b) {
a[a.length] = ',';
}
a.push(s.string(i), ':', v);
b = true;
}
}
}
a[a.length] = '}';
return a.join('');
}
return 'null';
},
'string': function (x) {
if (/[" ///x00-/x1f]/.test(x)) {
x = x.replace(/([/x00-/x1f//"])/g, function(a, b) {
var c = m[b];
if (c) {
return c;
}
c = b.charCodeAt();
return '//u00' +
Math.floor(c / 16).toString(16) +
(c % 16).toString(16);
});
}
return '"' + x + '"';
}
};
$.toJSON = function(v) {
var f = isNaN(v) ? s[typeof v] : s['number'];
if (f) return f(v);
};
$.parseJSON = function(v, safe) {
if (safe === undefined) safe = $.parseJSON.safe;
if (safe && !/^("( //.|[^"///n/r])*?"|[,:{}/[/]0-9./-+Eaeflnr-u /n/r/t])+?$/.test(v))
return undefined;
return eval('('+v+')');
};
$.parseJSON.safe = false;
})(jQuery);
var m = {
'/b': '//b',
'/t': '//t',
'/n': '//n',
'/f': '//f',
'/r': '//r',
'"' : '//"',
'//': '////'
},
s = {
'array': function (x) {
var a = ['['], b, f, i, l = x.length, v;
for (i = 0; i < l; i += 1) {
v = x[i];
f = s[typeof v];
if (f) {
v = f(v);
if (typeof v == 'string') {
if (b) {
a[a.length] = ',';
}
a[a.length] = v;
b = true;
}
}
}
a[a.length] = ']';
return a.join('');
},
'boolean': function (x) {
return String(x);
},
'null': function (x) {
return "null";
},
'number': function (x) {
return isFinite(x) ? '"' + String(x) + '"' : 'null';
},
'object': function (x) {
if (x) {
if (typeof x.splice == "function") {
return s.array(x);
}
if (!isNaN(x)) {
return s.number(x);
}
var a = ['{'], b, f, i, v;
for (i in x) {
v = x[i];
f = s[typeof v];
if (f) {
v = f(v);
if (typeof v == 'string') {
if (b) {
a[a.length] = ',';
}
a.push(s.string(i), ':', v);
b = true;
}
}
}
a[a.length] = '}';
return a.join('');
}
return 'null';
},
'string': function (x) {
if (/[" ///x00-/x1f]/.test(x)) {
x = x.replace(/([/x00-/x1f//"])/g, function(a, b) {
var c = m[b];
if (c) {
return c;
}
c = b.charCodeAt();
return '//u00' +
Math.floor(c / 16).toString(16) +
(c % 16).toString(16);
});
}
return '"' + x + '"';
}
};
$.toJSON = function(v) {
var f = isNaN(v) ? s[typeof v] : s['number'];
if (f) return f(v);
};
$.parseJSON = function(v, safe) {
if (safe === undefined) safe = $.parseJSON.safe;
if (safe && !/^("( //.|[^"///n/r])*?"|[,:{}/[/]0-9./-+Eaeflnr-u /n/r/t])+?$/.test(v))
return undefined;
return eval('('+v+')');
};
$.parseJSON.safe = false;
})(jQuery);
测试代码如下:代码基于struts2.(struts2的配置什么的,这里就不细说了+)
<%
...
@ page contentType="text/html; charset=UTF-8"
%>

<%
...
@ taglib prefix="s" uri="/struts-tags"
%>
<
html
>
<
head
>
<
meta
http-equiv
="Content-Type"
content
="text/html; charset=UTF-8"
/>
<
script
type
="text/javascript"
src
="js/jquery-1.2.1.pack.js"
></
script
>
<
script
type
="text/javascript"
src
="js/json-parser.js"
></
script
>

<
script
type
="text/javascript"
>
...

function addOption(objSelectNow,txt,val)...{
//使用W3C标准语法为SELECT添加Option
var objOption = document.createElement("OPTION");
objOption.text= txt;
objOption.value=val;
objSelectNow.options.add(objOption);
}
function addOptionGroup(selectId,optGroupString)...{
var optGroup = optGroupString.split(",");
var objSelect = document.getElementsByTagName("SELECT");
var objSelectNow = objSelect[selectId];
objSelectNow.length = 1;
//成组添加Options
for (i=0; i<optGroup.length; i++)...{
addOption(objSelectNow, optGroup[i], optGroup[i]);
}
}

function bindSelect(e, v) ...{
$("#"+e).append("<option value=''>请选择</option>");
$.each(v,function(k,value)...{
$("#"+e).append("<option value="+value[0]+">"+value[1]+"</option>");
});
$("#"+e).val('120000');
}

$(document).ready(function()...{
var json = '<s:property value="json_xml"/>';
json = json.replace(/"/g, '"');
var obj = jQuery.parseJSON(json);
$("#textId").val(obj.name);
addOptionGroup("selectId", obj.department.join(','));
//bindSelect('selectId', data.sf_dm);
//alert($("#selectId").children().eq(1).val());
//alert($("#selectId").children().eq(1).text());
//var option = document.createElement("OPTION");
//option.text = option.value = "1";
//alert(option.value);
//$("#selectId").append("<option value=''>请选择</option>");
//$("#selectId").append('<option value='1'>1</option>');
//$("<option value=''>请选择</option>").appendTo("#selectId");
//$('option:eq(1)', "#selectId").attr('text', '这是一个美丽的故事。');

if(obj.sex == 'M')...{
document.getElementById("m_radioId").checked = true;
} else ...{
document.getElementById("f_radioId").checked = true;
}

if(obj.age > 20)...{
document.getElementById("checkboxId").checked = true;
} else ...{
document.getElementById("checkboxId").checked = false;
}
$("#insrow").click(function()...{
var table = document.getElementById("tableId");
var index = table.rows.length;
var tr = table.insertRow(index);
for(var i=0; i<5; i++)...{
var td = tr.insertCell(i);
var input = document.createElement("input");
input.type="text";
input.value="田中";
td.appendChild(input);
}
});
$("#delrow").click(function()...{
var table = document.getElementById("tableId");
var index = table.rows.length;
if (index < 2)...{
alert("No Row To Delete!");
} else ...{
table.deleteRow(index - 1);
}
});
});

function testTbl()...{
var table = document.getElementById("tableId");
table.insertRow(1);
var rows = table.rows[0];
for(var i=0; i<rows.cells.length; i++)...{
var input = document.createElement("input");
input.type="text";
input.value="田中";
rows.cells[i].appendChild(input);
}
}

function testTable()...{
$("#tableId").append("<tr><td></td><td></td><td></td><td></td><td></td></tr>");
var table = document.getElementById("tableId");
var rows = table.rows;
for(var rs=0; rs<rows.length; rs++)...{
var cells = rows[rs].cells;
for(var cs=0; cs<cells.length; cs++)...{
var cell = cells[cs];
if(cell.tagName == 'TH')...{
break;
} else ...{
//var txtNode = document.createTextNode("aaaaaaa");
var input = document.createElement("input");
input.type="text";
input.value="田中"
cell.appendChild(input);
}
}
}
}

function testSelect()...{
$("#selectId").find('OPTION').each(function()...{
switch($(this).attr("value"))...{
case '1':
$(this).text("1");
break;
case '2':
$(this).text("2");
break;
default:
break;
}
});
}
</
script
>
</
head
>
<
body
>
<
form
>
Name:
<
input
id
="textId"
type
="text"
>
<
br
>
<
br
>
Department:
<
select
name
="selectId"
></
select
>
<
br
>
<
br
>
Male:
<
input
type
="radio"
name
="rad"
id
="m_radioId"
>
Female:
<
input
type
="radio"
name
="rad"
id
="f_radioId"
>
<
br
>
<
br
>
Age > 20:
<
input
type
="checkbox"
id
="checkboxId"
>
<
br
>
<
br
>
<
input
type
="button"
id
="insrow"
value
="行追加"
>
<
input
type
="button"
id
="delrow"
value
="行削除"
>
<
table
width
="483"
height
="35"
border
="1"
id
="tableId"
>
<
tr
>
<
th
>
Text
</
th
>
<
th
>
Radio
</
th
>
<
th
>
Checkbox
</
th
>
<
th
>
Select
</
th
>
<
th
>
TextArea
</
th
>
</
tr
>
</
table
>
</
form
>
</
body
>
</
html
>
本文介绍了一个基于Struts2框架的示例,展示了如何利用jQuery和自定义的JSON解析器来处理JSON数据。其中包括了JSON对象的创建、解析及在网页上的动态应用,如填充表单字段、下拉选项及表格等。
381

被折叠的 条评论
为什么被折叠?



