将JSON字符串解析为JavaScript对象原型或构造函数

x33g5p2x  于2022-10-16 转载在 Java  
字(1.7k)|赞(0)|评价(0)|浏览(545)

在本文中,我将向您展示如何将JSON字符串解析为特定的JavaScript对象或构造函数(即使用特定的原型)。
JavaScript提供JSON。parse()API将JSON字符串解析为JavaScript对象。但在本文中,我向您展示了如何使用构造函数将JSON字符串解析为JavaScript对象原型。

将JSON字符串解析为JavaScript对象原型或构造函数

让我们创建一个JavaScript构造函数:

function Post(){
    this.id = "";
    this.title = "";
    this.description = "";
    this.postedUser = new User();
}

function User(){
    this.id="";
    this.name = "";
    this.age = "";
}

为了进行测试,我们需要用JavaScript创建一个JSON对象,如:

var json2 = {
    "post" : {
        "id" : "1",
        "title" : "post title",
        "description" : "post description",
        "postedUser" : {
            "id" : "1",
            "name" : "Ramesh",
            "age" : "29"
        }
    }
}

现在,我们创建一个JavaScript函数,将上面的JSON解析为JavaScript对象:

function demo(){
    // parse to json string
    var jsonStr = JSON.stringify(json2);

    // parse json string into JavaScript Object
    var object = JSON.parse(jsonStr);

    console.log(object);
    console.log(object.getTitle());
}

demo();

完成代码和输出

function Post(){
    this.id = "";
    this.title = "";
    this.description = "";
    this.postedUser = new User();
}

function User(){
    this.id="";
    this.name = "";
    this.age = "";
}

var json2 = {
    "post" : {
        "id" : "1",
        "title" : "post title",
        "description" : "post description",
        "postedUser" : {
            "id" : "1",
            "name" : "Ramesh",
            "age" : "29"
        }
    }
}

function demo(){
    // parse to json string
    var jsonStr = JSON.stringify(json2);

    // parse json string into JavaScript Object
    var object = JSON.parse(jsonStr);

    console.log(object);
    console.log(object.getTitle());
}

demo();

为了获得最佳学习体验,我强烈建议您打开一个控制台(在Chrome和Firefox中,可以通过按Ctrl+Shift+I来完成),导航到“控制台”选项卡,复制并粘贴本文中的每个JavaScript代码示例,然后按Enter/Return键来运行它。

相关文章

微信公众号

最新文章

更多