-2

I am trying to create one HTML file that has JSON data embedded in it. The one file can then use the JSON data to create HTML such as a table and so forth.

I have tried template literals, but I'm not sure if I am doing it correctly or what I am missing. This the first time I'm doing this, so I'm not sure how to proceed.

Here's a basic example that I saved as sample.html

const person = {
name: 'Test',
job: 'A job',
city: 'a city',
bio: 'What a test that I'm doing!'
}

// And then create our markup:

const markup = `
 <div class="person">
<h2>
    ${person.name}
</h2>
<p class="location">${person.location}</p>
<p class="bio">${person.bio}</p>
 </div>`;

When I view the results, I only see the JSON string and the literal ${person.name} instead of the data within the JSON string. I want it to extract'Test', 'A City', 'What a test that I'm doing' from the Json and then display it using HTML. However, it should all live in one document. Thank you in advance for viewing my question!

yanci
  • 163
  • 1
  • 13
  • 1
    It works fine if you fix the typo (unescaped `'` in a string delimited by `'`). https://jsbin.com/kugajabiqi/1/edit?js,console – Quentin Jul 15 '19 at 16:49
  • Your JSON isn't JSON, it is JavaScript. – Quentin Jul 15 '19 at 16:49
  • https://jsbin.com/kaseguv/edit?js,console,output – Mosh Feu Jul 15 '19 at 16:50
  • sorry, but I'm not understanding... I tried changing the type but my display still shows const person = {name: "Test",job: "A job",city: "a city",bio: "What a test that I'm doing!" } // And then create our markup: const markup = ` ${person.name} ${person.location} ${person.bio} `; – yanci Jul 15 '19 at 17:00
  • I was trying to following this example..but it's not working for me https://www.youtube.com/watch?v=DG4obitDvUA – yanci Jul 15 '19 at 17:02
  • If you put your JavaScript source code, outside of a ` – Quentin Jul 15 '19 at 17:03

1 Answers1

0

Below is what worked for me.

<!DOCTYPE html>
<html>
<body>

<h2>Create Object from JSON String</h2>

<p id="demo"></p>

<script>
var text = '{"person":[' +
'{"name":"Test","job":"a job", "city":"a city", "bio": "What a test that I am doing" }]}';

obj = JSON.parse(text);
document.getElementById("demo").innerHTML =
obj.person[0].name + " " + obj.person[0].bio;
</script>

yanci
  • 163
  • 1
  • 13