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

时间:2019-04-08 11:17:49

标签: javascript node.js sequelize.js

我已将字符串格式的数据更改为[对象对象]的格式,但是我想将字符串对象更改为我尝试过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]

3 个答案:

答案 0 :(得分:2)

据我所知,您已经使用var obj = JSON.parse(cont1);

将其转换为JSON。

所以您已经有了一个JSON,只是您打印它的方式是错误的。用逗号代替+。

console.log('data as json', obj)

+正在执行字符串连接,并且正在尝试将字符串与对象进行连接

答案 1 :(得分:0)

在字符串连接之后,它将打印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));

答案 2 :(得分:0)

console.log只是对象; 如果要使用log对象和字符串,请使用而不是+

jsonString = '{"key1":"value1","key2":"value2"}'

jsonObject = JSON.parse(jsonString)

console.log(jsonObject) // logging just the object

console.log('jsonObjectName' , jsonObject) // logging object with string 

console.log('jsonObject.key1 : ' +  jsonObject.key1 ) 


// this may come handy with certain IE versions
function parseJSON(resp){
    if (typeof resp === 'string') 
        resp = JSON.parse(resp);
    else
        resp = eval(resp);
    return resp;
}