我正在使用Editor.js它将数据输出为 JSON 并将其保存为 DynamoDB 中的字符串。当我查询该数据时,我想将其转换回对象。
使用 JSON.parse()
转换字符串会给出 Error: Unexpected token t in JSON atposition 1
消息。
var json = '{time=1558311121067, blocks=[{type=paragraph, data={text=writing something first}}], version=2.13.0}';
obj = JSON.parse(json);
不确定此错误消息的含义。
最佳答案
如果可以的话,我建议从源本身更正 JSON,
如果不能,则需要将 =
替换为 :
,然后使用 stringify
和 parse
({[^=]+|,[^=]+)=
| |_________ Replaces `=` which is preceded by `,`
|_________________ Replaces `=` which is preceded by `{`
let json = '{time=1558311121067, blocks=[{type=paragraph, data={text=writing something first}}], version=2.13.0}';
json = json.replace(/({[^=]+|,[^=]+)=/g,"$1"+':')
let obj = JSON.parse(JSON.stringify(json));
console.log(obj)
旁注:-这是考虑上面给定示例数据的代码,它可以根据 JSON 可以具有的值类型进行更新
关于javascript - 使用 Javascript 将字符串转换为对象(错误 : Unexpected token t in JSON at position 1),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56213414/