Print more than one value with json

Asked

Viewed 40 times

3

How can I show the name, age and city at the same time on the screen and not just the name?

document.getElementById("demo").innerHTML = obj.name;

makes it show only the name inside that obj but I wanted to appear all the information about that obj.

// Storing data:
myObj = {name: "John", age: 31, city: "New York"};
myJSON = JSON.stringify(myObj);
localStorage.setItem("testJSON", myJSON);

// Retrieving data:
text = localStorage.getItem("testJSON");
obj = JSON.parse(text);
document.getElementById("demo").innerHTML = obj.name;

2 answers

2


Just concatenate the values you want to print.

// Storing data:
obj = {name: "John", age: 31, city: "New York"};

// document.body.innerHTML = obj.name + " " + obj.age + " " + obj.city;
document.body.innerHTML = `${obj.name} ${obj.age} ${obj.city}`;

See this article

  • It worked! Thank you!

  • 1

    @Davidmv just be sure to mark this answer as correct, so people with the same problem can also be helped

1

Try to do so:

document.getElementById("demo").innerHTML = obj.name,obj.age,obj.city;

I only used JSON with C#, so I think the logic is similar

  • 1

    I’ve tried that and it also doesn’t work :( but thanks anyway

Browser other questions tagged

You are not signed in. Login or sign up in order to post.