Why I am getting this error when I want to parse a JSON?

const list = {
    "status": "success",
    "messages": [
        "some message 1",
        "some message 2"
    ],
    "data": {
        "headers": [
            {
                "id": {
                    "title": "ID",
                    "sortable": true,
                    "hidden": false,
                    "searchable": true
                },
                "name": {
                    "title": "Name",
                    "sortable": true,
                    "hidden": false,
                    "searchable": true
                },
                "message": {
                    "title": "Feedback Message",
                    "sortable": false,
                    "hidden": false,
                    "searchable": false
                },
                "created_at": {
                    "title": "Submision Date",
                    "sortable": true,
                    "hidden": false,
                    "searchable": true
                }
            }
        ],
        "rows": [
            {
                "id": 111,
                "name": "Mizan",
                "message": "",
                "created_at": "2020-08-12"
            },
            {
                "id": 121,
                "name": "Atiq",
                "created_at": "2020-08-13"
            },
            {
                "id": 131,
                "name": "Anik",
                "message": "test",
                "created_at": "2020-08-14",
                "extra_junk_field": "i will not be shown in the table"
            },
            {
                "id": 141,
                "name": "Subbir",
                "message": "wow",
                "created_at": "2020-08-13"
            }
        ]
    }
};

const parsedList = JSON.parse(list);

console.log(parsedList);

When I run this code why this is producing this error?

PS C:\Users\mizanmahi\Desktop\react-list-project> node .\src\components\playGround.js
undefined:1
[object Object]
^

SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse ()
at Object. (C:\Users\mizanmahi\Desktop\react-list-project\src\components\playGround.js:65:25)
at Module._compile (node:internal/modules/cjs/loader:1109:14)
at Object.Module._extensions…js (node:internal/modules/cjs/loader:1138:10)
at Module.load (node:internal/modules/cjs/loader:989:32)
at Function.Module._load (node:internal/modules/cjs/loader:829:14)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12)
at node:internal/main/run_main_module:17:47

You’re parsing an object instead of a string.

JSON.parse() = convert a string into a javascript object
JSON.stringify() = convert a javascript object to a string

2 Likes

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.