Reputation: 7504
Below is my json file, I want to put src
for my img element.
How can I access value from my json using keys img1, img2, img3...
as I am already looping through.
json file:
{
"img1": "http://yui.yahooapis.com/testassets/museum.jpg",
"img2": "http://yui.yahooapis.com/testassets/uluru.jpg",
"img3": "http://yui.yahooapis.com/testassets/katatjuta.jpg",
"img4": "http://yui.yahooapis.com/testassets/morraine.jpg",
"img5": "http://yui.yahooapis.com/testassets/japan.jpg"
}
Ejs file:
<% var img_content = JSON.parse(json['img-load.json']); %>
<body>
<% for(var i = 1; i <= 5; i++ ) { %>
<img id="img<%= i %>" src="<%= img_content[i] %>" />
<% } %>
</body>
</html>
Upvotes: 0
Views: 57
Reputation: 29102
I think you need img_content['img' + i]
, like this:
<% var img_content = JSON.parse(json['img-load.json']); %>
<body>
<% for(var i = 1; i <= 5; i++ ) { %>
<img id="img<%= i %>" src="<%= img_content['img' + i] %>" />
<% } %>
</body>
</html>
The []
work just the same as they would in normal JS code.
Upvotes: 1