3

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

Tenzolinho
  • 922
  • 2
  • 15
  • 35

5 Answers5

3

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

Aagam Jain
  • 1,546
  • 1
  • 10
  • 18
2

The problem was that I didn't parse the right thing. Here is the correct snippet:

let p = JSON.parse(data.project);

  this.employees.push({
  projectName: p.projectName,
  poNumber: p.poNumber
})

Thank you everyone for help! Every answer of you was right.

Tenzolinho
  • 922
  • 2
  • 15
  • 35
1

Try like this :

JSON.parse(data).array.forEach(element => {
  this.employees.push({
    projectName: element.project.projectName,
    poNumber: element.project.poNumber
  })
})
Shashikant Devani
  • 2,298
  • 1
  • 12
  • 25
1

I was getting same error in JSON format, but after validating it on online JSON validator it seems perfect. On the basis of that I have created following example which shows two diffrent ways to get data in your "employees" array.

I hope this will be helpful.

let data = {
 "id":1,"name":"john doe",
  "project":[
        {
  "projectName": "proj1",
  "poNumber": "1"
 },
        {
  "projectName": "proj2",
  "poNumber": "2"
 }
    ]
};

let employees = [];


Object.keys(data).map(key => {
    if(key === 'project') {
        // Method 1
        // ===========================
        data[key].map(obj => {
            employees.push(obj);
        });
        
        // Method 2 : Shorter method
        // ===========================
        employees.push(...data[key]);
    }
});

console.log('Employees :', employees);

Thanks, Jignesh Raval

Jignesh Raval
  • 587
  • 7
  • 15
0
JSON.parse(data).array.forEach(element => {
     this.employees.push({
        projectName: element.project.projectName,
        poNumber: element.project.poNumber
     })
});
Sanoj_V
  • 2,936
  • 1
  • 12
  • 28