Skip to content
Advertisement

JAVASCRIPT JSON.parse() return Unexpected end of JSON input

I have a response from a service, using https

rest.on("data", data => {
  response = JSON.parse(data);
});

I need parse this response but… I know the final result should be(I get this with postman)…

{ "code": 200,
"msg": "",
"data": [
    {
        "id": "t4ba",
        "devData": {
            "id": "bb2as",
            "state": "OK"
        },
        "entries": {
            "2019-05-26T19:03:13.9260000": 15,
            "2019-05-26T19:03:29.1690000": 26,
            "2019-05-26T19:04:16.6880000": 65
        }
    },
    {
        "id": "t4ba-2",
        "devData": {
            "id": "bb2as",
            "state": "Underperformance"
        },
        "entries": {
            "2019-05-26T19:03:13.9260000": 25,
            "2019-05-26T19:03:29.1690000": 45,
            "2019-05-26T19:04:16.6880000": 32
        }
    }
],
"dateResponse": "2021-03-26T19:04:16.6880000" }

When I run JSON.parse(data)

I get this errror

“errorType”: “SyntaxError”, “errorMessage”: “Unexpected end of JSON input”, “trace”: [ “SyntaxError: Unexpected end of JSON input”, ” at JSON.parse ()”, ” at IncomingMessage. (/var/task/index.js:47:23)”, ” at IncomingMessage.emit (events.js:315:20)”, ” at IncomingMessage.EventEmitter.emit (domain.js:467:12)”, ” at IncomingMessage.Readable.read (internal/streams/readable.js:519:10)”, ” at flow (internal/streams/readable.js:992:34)”, ” at resume_ (internal/streams/readable.js:973:3)”, ” at processTicksAndRejections (internal/process/task_queues.js:80:21)” ]

I think the “data array” field is the problem and I don’t know how to solve it.

When I receive a response with empty data:[], everything works fine.

Advertisement

Answer

Hmmmm… The answer is easy…

Lets Start:::::

First, looks like you get a lot of data from your service…

On response.on(“data”

Data is not complete at first, so, .on(“data” “repeat himself” from init to end, then ur data is complete…

code

res.on("data", data => {
  someVariable += data;
});

then… in your .on(“end”

rest.on("end", () => {
  MyJSON = JSON.parse(someVariable);
});

That’s all folks.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement