1

My API return user object and format is like that=>

{'id': '1', 'username': 'admin', 'image': 'https://user/testing.png', 'phno': '123'}

First I do JSON.stringify and I check the type of this line is a string.

So I use JSON.parse to get an object but its still string and can't get it likes user.id is undefined.

How can I get like user.id, user.username,...?

console.log(user);
console.log(user.user);

var test = JSON.stringify(user.user);
console.log(typeof(test));

var test1 = JSON.parse(test);
console.log(test1.id);

enter image description here

0

3 Answers 3

2

I think the problem might be that your API is returning JSON data with single quotation marks, and JavaScript is not able to parse it correctly. Check which JSON serializer you're using on server side. It should be like: {"id": "1", "username": "admin", "image": "https://user/testing.png", "phno": "123"}.

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

Comments

0

This solution works for your data:

var data = '{"id": "1", "username": "admin", "image": "https://user/testing.png", "phno": "123"}';
var user = JSON.parse(data);
console.log(user.id);

1 Comment

A notice - JSON format is supposed to have " in it, not single quotes
0

It seems like you are not getting exact user json. Issue may be backend.

const obj = `{"user":"{\\"id\\": \\"1\\", \\"username\\": \\"admin\\", \\"image\\": \\"https://user/testing.png\\", \\"phno\\": \\"123\\"}"}`
console.log(obj)
// First get value of user.
let user = JSON.parse(obj).user
console.log(typeof user) //string
// parse again, since user is string
user = JSON.parse(user)
console.log(user.username)
console.log(user.id)

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.