0
I am trying to figure out how to take an array of arrays and convert it to a json string to return via a REST api.

My server gets records from a database. Each record is in the form:

    {"user":"some name","age":number}

I need to return the data in json format so that the REST specification is valid. Sometimes I get a single record to return other times I get multiple records. Below is a sample script I am using to test the syntax for converting into json format.

var resultSet = [];
resultSet.push({"user":"John Doe","age":43});
resultSet.push({"user":"Jane doe","age":29});
var myJson = JSON.parse(resultSet);

When I run this code using nodejs I get the following error:

SyntaxError: Unexpected token o in JSON at position 1
    at JSON.parse (<anonymous>)

Any suggestions would be very appreciated.

1
  • resultSet is not JSON. Please be aware that a JS object/array is not JSON. Commented Mar 31, 2021 at 0:26

1 Answer 1

1

JSON.parse expects a string. You are passing an Array.

This works because the input is a string:

JSON.parse('[{"foo": "bar"}]')

This doesn't work because the input is an Array:

JSON.parse([{"foo": "bar"}])

Are you trying to return an Array or a string? If you are trying to return a string, then you should use JSON.stringify like this:

JSON.stringify([{"foo": "bar"}])
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.