如何在JavaScript中将字符串对象转换为json对象

我已将字符串格式的数据更改为类似于[对象对象]的格式,但我想将字符串对象更改为我尝试过json.parse的json对象,但未将其更改为json对象


你能建议我哪里做错了以及如何解决这个问题


try {

  var timekeep = await Orders.findAndCountAll({

    where: {

      cid: orders_info.cid,

    },

    order: [

      ['id', 'DESC']

    ],

    limit: 1,

    raw: true,

  });

  var cont1 = JSON.stringify(timekeep.rows[0]);

  var obj = JSON.parse(cont1);

} catch (err) {

  console.log(err)

}


console.log('org data' + timekeep)

console.log('data as string' + cont1);


// now when I am trying to print

console.log('data as json' + obj);

console.logs的输出


org data [object Object]


data as sttring{"id":4006,"mid":1,"cid":41,"wid":7138,"oid":null,"status":null,"options":null,"starttime":"2018-08-15T06:08:55.000Z","duration":null,"ordertotal":50,"counter":null,"closetime":null}


data as json [object object]


米琪卡哇伊
浏览 151回答 3
3回答

哆啦的时光机

据我所知,您已经将其转换为JSON var obj = JSON.parse(cont1);因此,您已经有了一个JSON,只是您打印它的方式是错误的。以逗号代替+。console.log('data as json', obj)+正在执行字符串连接,并且正在尝试将字符串与对象连接

侃侃无极

在String concat之后,它会打印data as json [object object]。如果您放置,而不是+将正确打印该对象。在摘要中,您可以看到不同之处。var jsonstr = '{"id":4006,"mid":1,"cid":41,"wid":7138,"oid":null,"status":null,"options":null,"starttime":"2018-08-15T06:08:55.000Z","duration":null,"ordertotal":50,"counter":null,"closetime":null}';console.log(JSON.parse(jsonstr));console.log('data as json' , JSON.parse(jsonstr));console.log('data as json' + JSON.parse(jsonstr));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript