3

TypeScript throws an error when using JSON.parse(). When I pass it this json data:

{
    "AXzgeQ7vXOjWnFrgjHiM": {
        "0-17-13955610754117-8-2021": {
            "channelId": "17", 
            "end": "1642091400000", 
            "id": "0-17-13955610754117-8-2021", 
            "start": "1642090860000", 
            "title": "Yle Uutiset Alueeltasi", 
            "type": "broadcast"
        }
    }
}

Which is imported like: import stubReminders from './stub_data.json';

It throws the error:

Argument of type '{ AXzgeQ7vXOjWnFrgjHiM: { "0-17-13955610754117-8-2021": { channelId: string; end: string; id: string; start: string; title: string; type: string; }; }; }' is not assignable to parameter of type 'string'.ts(2345)

What should I change to successfully use JSON.parse()?

2 Answers 2

2

The JSON.parse function takes a string as parameter. You are trying to pass an object to it. So you have to convert it to a string before, if you want to use JSON.parse.

But keep in mind, that the imported object already is an object, so I think there is no need to parse it.

const obj = {
    "AXzgeQ7vXOjWnFrgjHiM": {
        "0-17-13955610754117-8-2021": {
            "channelId": "17", 
            "end": "1642091400000", 
            "id": "0-17-13955610754117-8-2021", 
            "start": "1642090860000", 
            "title": "Yle Uutiset Alueeltasi", 
            "type": "broadcast"
        }
    }
}



console.log(JSON.parse(JSON.stringify(obj)))
Sign up to request clarification or add additional context in comments.

Comments

1

Try accessing your imported stubReminders as is without trying to parse it. I have tested out an example, and the import parses the JSON automatically.

I hope this works.

Also checkout this codesandbox link.

1 Comment

Thank you, I had no idea it was automatically parsed on import!

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.