Working with JSON without a JavaScript framework

Hey,
This is my first time posting here and i’m hoping for some help. I’m a beginner in JavaScript so i’m trying to learn.

.col.s12.m4
	.card.small
		.card-image
			img(src="http://placehold.it/100x50")
			span.card-title Title
		.card-content
			p Card with some text
		.card-action
			a(href="#!") Link
{"projects":[
	{
		"image":"http://placehold.it/150x50",
		"title":"Project 1",
               "content":"content project 1",
		"link":"#"
	},
	{
		"image":"http://placehold.it/100x50",
		"title":"Project 2",
                "content":"content project 2",
		"link":"#"
	},
	{
		"image":"http://placehold.it/155x50",
		"title":"Project 3",
                "content":"content project 3",
		"link":"#"
	}
]}

I would like to have data from my JSON to be used inside these Jade(now PUG) parts. For example Title would be projects.title. Now I know this can be done with node, angular or other frameworks but i’d like to learn JavaScript without using any frameworks. Could anyone point me in a direction how to do this in plain JavaScript?

This begs the question…

So, why are you using Jade(now PUG)? :wonky:

coothead

Since that isn’t a JavaScript framework. I use Jade for my html and sass for my css. but i’d like to start with plain Javascript instead of jQuery, angular and sorts.

That is so sad. :unhappy:

coothead

Hey @robbin_jagt,

JSON is very easy to work with in vanilla JavaScript. All modern browsers (and IE8+) have a built-in JSON object that has the methods parse() and stringify(), which convert from a string of JSON to JS values and vice-versa, respectively.

What are you wanting to do? Load JSON from the server and render it via PUG, or something like that?

That’s the idea yes. Render the data from my JSON in to my PUG by using javascript. I’ve done some research but all i’ve been them do is render it in a table.

	- for (var i = 0; i < 3; i++)
					include cards.jade

In the PUG code I included is the cards.jade I load in here. so I want the code to be repeated three times, which works fine. but all of them filled with the data gained from the JSON. (The cards all have unique data gained from the same JSON).

Why is it? I like PUG since it makes it quicker to write my html and it has some added functions. Same for Sass, I can create a vars and that way change the looks of the site with 1 var instead of replacing every color on every element desperately.

I’ve just tried out the following, which worked fine for me:

main.pug

div
  each project in projects
    include cards.pug

cards.pug

.col.s12.m4
  .card.small
    .card-image
      img(src=project.image)
      span.card-title #{project.title}
    .card-content
      p Card with some text
    .card-action
      a(href=project.link) Link

main.js

const pug = require('pug');
const projects = [
  {
    "image":"http://placehold.it/150x50",
    "title":"Project 1","content":"content project 1",
    "link":"/project1"
  },
  {
    "image":"http://placehold.it/100x50",
    "title":"Project 2","content":"content project 2",
    "link":"/project2"
  },
  {
    "image":"http://placehold.it/155x50",
    "title":"Project 3","content":"content project 3",
    "link":"/project3"
  }
];

const tpl = pug.compileFile('mytpl.pug');
const html = tpl({ projects });

console.log(html);

Here’s a snippet of the output:

<div>
  <div class="col s12 m4">
    <div class="card small">
      <div class="card-image">
        <img src="http://placehold.it/150x50"/>
        <span class="card-title">Project 1</span>
      </div>
      <div class="card-content">
        <p>Card with some text</p>
      </div>
      <div class="card-action"><a href="/project1">Link</a></div>
    </div>
  </div>

I will test that and see how it works for me. I have two questions though, if you don’t mind. Is it possible to do this with an ,json file for the data instead of having it build within the JavaScript file. and could you explain a bit how this actually works? I have worked with ‘const’ in some tutorials i’ve followed but

const tpl = pug.compileFile('mytpl.pug');
const html = tpl({ projects });

is quite a mystery for me. So if you could tell me a little more about that I would greatly appreciate it.

I should point out that the code I posted was running in Node, rather than the browser - that seemed to be the easiest way to test out pug.

Could you share some code to help me understand what sort of setup you’re using? I’m assuming you’re wanting to do this client-side (i.e. in the browser)? How are you wanting to load the JSON - are you trying to avoid jQuery altogether (i.e. you want to make a vanilla JS Ajax request)?

const was introduced in the ES6 release of JS to create constants - it basically prevents you from reassigning a different value to the constant elsewhere in the code. The example below will throw a type error:

const name = "Freddy";
name = "Brian";

My set up is quite basic I must say.

html

	include head.jade

	body

		include header.jade

		include carousel.jade
		
		.container
			.row
				each project in projects
					include cards.jade

		include footer.jade

Other than Sass and Pug i’m using materialize.css for this project. At this moment it’s just a playground for me to test and try new techniques I could use in future projects. I’m not trying to avoid jQuery all together but i’d like to use plain JavaScript where it’s possible, just so I get to know JavaScript and not just frameworks/libraries.

All of this is indeed done in the browser, as for loading in the JSON I was thinking of doing so with AJAX.

When I tried your code I tried your code I did get an error: ’ Cannot read property ‘length’ of undefined on line 13’

Are you rendering this locally (like a static site generator) or server-side? Looking at the template you’ve posted, that’s a full page, including the <html> tag, so I’m guessing you’re not doing client-side templating as I’d thought?

If you could share enough code that I recreate a simple setup on my machine that’d help me work out what’s going on.

This is a jsfiddle with the compiled index.html and the custom js. https://jsfiddle.net/eq6feLv6/

Also get http://materializecss.com/getting-started.html and get the sass version, that’s where my classes / js comes from.

At this moment i’m just making this site in sublime text, not using node or anything else than my local files.

But how are you compiling the template? Are you using the command-line utility?

Atm i’m using prepos as a compiler. I’m not yet using the command line, it’s one of the things that’s on my list though.

Ahhh, OK. I don’t think there is a way to load JSON data into your template when compiling with prepros unfortunately (although I’m not a Mac user, so maybe someone else knows differently).

It seems that if you use the Pug CLI to compile templates, you can specify a JSON file to use as input.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.