16.JavaScript之json

2019-08-20  本文已影响0人  讲武德的年轻人

string变json

1.用eval函数
eval()自己产生一个string,当作js脚本,交由js引擎处理
2.JSON.parse()
3.jQuery.parseJSON()

json变string

1.JSON.stringify()
2.jQuery.toJSON()

json一个简单应用实例

var oStdTable = {};
oStdTable.students = [];

var student = {
    'name': '小明',
    'birthday': '1988-03-08',
    'class': '一班',
    'scales': [
        {
            'course': '语文',
            'scale': 92
        },
        {
            'course': '数学',
            'scale': 97
        },
        {
            'course': '英语',
            'scale': 88
        }
    ]
};
oStdTable.students.push(student);

var student = {
    'name': '小红',
    'birthday': '1987-09-05',
    'class': '二班',
    'scales': [
        {
            'course': '物理',
            'scale': 92
        },
        {
            'course': '化学',
            'scale': 97
        }
    ]
};
oStdTable.students.push(student);

var student = {
    'name': '小齐',
    'birthday': '1990-05-01',
    'class': '一班',
    'scales': [
        {
            'course': '历史',
            'scale': 92
        },
        {
            'course': '地理',
            'scale': 97
        }
    ]
};
oStdTable.students.push(student);


var sStdTable = JSON.stringify(oStdTable);
console.log(sStdTable);

var jsonTable = JSON.parse(sStdTable);
for(var x in jsonTable.students){
    console.log(jsonTable.students[x].name);
    console.log(jsonTable.students[x].birthday);
    console.log(jsonTable.students[x].class);
    
    var scales = jsonTable.students[x].scales;
    for(var y in scales){
        console.log('    ' + scales[y].course + ':' + scales[y].scale );
    }
}
输出截图

json的使用,简单而重要!!!

上一篇 下一篇

猜你喜欢

热点阅读