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

6
  • whats is [object Object] in data? Commented Sep 17, 2018 at 12:47
  • This is how my entry looks into my database, I posted it using postman, but project has the format I wrote in my question. Commented Sep 17, 2018 at 12:50
  • Can you add console in element and post consoled data into your question. Commented Sep 17, 2018 at 12:50
  • 1
    try data.project.forEach. Commented Sep 17, 2018 at 12:51
  • 1
    use JSON.parse(data.project). //logic and check project list is valid or not. ie. it is properly formatted or not using JSON.stringify() Commented Sep 17, 2018 at 13:02

5 Answers 5

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, you made me realize what I did wrong. I have to save the data first with JSON.stringify(x)
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.

Comments

1

Try like this :

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

Comments

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

Comments

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

1 Comment

A good answer has a better explanation How do I write a good answer?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.