.
3ss.cn

Javascript中JS对象与JSON的相互转换

1.JSON.stringify():js对象->json

  <script>
         //Number
        console.log(JSON.stringify(3.14));
        //字符串
        console.log(JSON.stringify('php.cn'));
        //布尔型
        console.log(JSON.stringify(true));
        console.log(JSON.stringify(null));
        //对象
        console.log(JSON.stringify({x:'a',y:'b'}));
        //数组
        console.log(JSON.stringify([1,2,3]));
  </script>

2.JSON.parse(): json->js对象

    <script>
        console.log(JSON.parse(
            `{
                "a":1,
                "b":2,
                "c":3
            }`
        ));
        console.log(typeof JSON.parse(
            `{
                "a":1,
                "b":2,
                "c":3
            }`));
        let jsObj=JSON.parse(`{"a":1,"b":2,"c":3}`);
        //判断是否为Object
        console.log(jsObj instanceof Object);
        console.log(typeof jsObj);
        //promise fetch
    </script>

推荐:《2021年js面试题及答案(大汇总)》

赞(0)
未经允许不得转载:互联学术 » Javascript中JS对象与JSON的相互转换

评论 抢沙发