parse [object Object] Angular 6

Tenzolinho picture Tenzolinho · Sep 17, 2018 · Viewed 7.2k times · Source

I want to parse a string and save projectName and poNumber into 2 variables. This is what I have by now, using JSON.parse()

employees = []
JSON.parse(data).array.forEach(element => {
    this.employees.push({
      projectName: element.projectName,
      poNumber: element.poNumber
    })
  });

console.log(employees['projectName'])
console.log(employees['poNumber'])

where data has this format:

{"id":1,"name": "john doe", "project":"[object Object]"}

and project looks like:

"project": [
     {
        "projectName": "proj1",
        "poNumber": "1"
     }
]

But I get this error

ERROR SyntaxError: Unexpected token o in JSON at position 1

Where am I mistaking? Thank you for your time!

EDIT: I understood why I get this error, because my data is already an object and there is no need to use JSON.parse(), but my code is still not working because I get the error:

core.js:1671 ERROR TypeError: Cannot read property 'forEach' of undefined

Answer

Aagam Jain picture Aagam Jain · Sep 17, 2018

Your Json String is not valid and is not stringified by JSON.stringify() instead it was stringified by toString method, otherwise nested objects were stringified properly.

enter image description here