0

I'm using Editor.js which outputs data as JSON and save that as String in DynamoDB. When I query that data, I want to convert that back to an Object.

Converting the string with JSON.parse() gives me Error: Unexpected token t in JSON at position 1 message.

var json = '{time=1558311121067, blocks=[{type=paragraph, data={text=writing something first}}], version=2.13.0}';
obj = JSON.parse(json);

Not sure what this error message means.

7
  • 2
    That isn't JSON. It has no quotation marks and is using = to assign values, instead of :. In the future, consider some of the many JSON validators/linters out there to verify your JSON whenever you see error messages like this. Commented May 20, 2019 at 1:37
  • @TylerRoper Thank you for the answer. Unfortunately, that how Editorjs outputs the data. Does it mean that I have to modify the format of the data to be able to convert that string to object? Commented May 20, 2019 at 1:40
  • 1
    You can either format the output to be valid JSON, or write a custom parser for the format that it's currently outputting. That said, I'd do some research to make sure that Editor.js can't output valid JSON. Commented May 20, 2019 at 1:43
  • @TylerRoper yeah, based on the editorjs website, it looks like they should be providing valid JSON. My guess would be possibly improper use of the API Commented May 20, 2019 at 1:44
  • @TylerRoper Got ya! Thank you for the help. Just noticed that Editor.js actually outputs valid JSON format. When it's being saved in DynamoDB via Appsync GraphQL it converts to that weird format lol Commented May 20, 2019 at 1:47

1 Answer 1

3

I will suggest to correct the JSON from the origin itself if you can,

if you can't than you need to replace = with : and than stringify and 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)

On side note:- This is code is considering above given example data, it can be updated based on the kind of values your JSON can have

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.