0

When I query a database, I receive a string as follows:

{
 S: '[{"firstName":"Max","lastName":"Mustermann","age":40},{"firstName":"Hagbard","lastName":"Celine","age":44},{"firstName":"Karl","lastName":"Koch","age":42}]'
}

How can I go about converting the string above to JSON objects to receive something like this:

var someData = [
 {firstName: "Max", lastName: "Mustermann", age: 40},
 {firstName: "Hagbard", lastName: "Celine", age: 44},
 {firstName: "Karl", lastName: "Koch", age: 42},
];

Would appreciate any assistance at all, thank you very much!

asked Oct 21, 2020 at 0:05
5
  • 2
    have you tried someData = JSON.parse(someObj.s)? Commented Oct 21, 2020 at 0:07
  • you can use JSON.parse(yourdata) Commented Oct 21, 2020 at 0:08
  • Hi, when I use that I get Error [SyntaxError]: Unexpected token o in JSON at position 1 Commented Oct 21, 2020 at 0:09
  • First JSON.stringify(someData) and then parse it. Seems like you're already passing a string version of a JSON object Commented Oct 21, 2020 at 0:12
  • @Halmon Yes, I wanted to convert that string version back to a JSON object but seem to be getting Error [SyntaxError]: Unexpected token o in JSON at position 1 while using JSON.parse(yourdata) Commented Oct 21, 2020 at 0:14

1 Answer 1

1

const receivedFromDB = {
 S: '[{"firstName":"Max","lastName":"Mustermann","age":40},{"firstName":"Hagbard","lastName":"Celine","age":44},{"firstName":"Karl","lastName":"Koch","age":42}]'
};
const arrayOfData = JSON.parse(receivedFromDB.S);
console.log(arrayOfData);

answered Oct 21, 2020 at 0:14
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much! Works perfect, I was missing the '.S'. I am waiting to accept your answer in 2 mins time :)

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.