The 10 Best Free Magazine & News WordPress Themes in 2021

Launching an online magazine is an exciting business venture. Sharing stories and news about topics that interest you is a great way to connect with other like-minded people and build authority in a particular niche. But, before you launch your online magazine, you will need a magazine or a news theme that will help you…

Quick Tip: How to Loop Through a JSON Response in JavaScript

Quick Tip: How to Loop Through a JSON Response in JavaScript – SitePointSkip to main contentFree JavaScript Book!Write powerful, clean and maintainable JavaScript.RRP $11.95 When fetching data from a remote server, the server’s response will often be in JSON format. In this quick tip, I’ll demonstrate how you can use JavaScript to parse the server’s response, so as to access the data you require.
This process will typically consist of two steps: decoding the data to a native structure (such as an array or an object), then using one of JavaScript’s in-built methods to loop through that data structure. In this article, I’ll cover both steps, using plenty of runnable examples.
What is JSON?
Before we look at how to deal with JSON, let’s take a second to understand what it is (and what it isn’t).
JSON stands for JavaScript Object Notation. It’s a language-independent, text-based format, which is commonly used for transmitting data in web applications. JSON was inspired by the JavaScript Object Literal notation, but there are differences between the two. For example, in JSON keys must be quoted using double quotes, while in object literals this is not the case.
There are two ways data can be stored in JSON:
a collection of name/value pairs (aka a JSON object)
an ordered list of values (aka a JSON array)
When receiving data from a web server, the data is always a string, which means that it’s your job to convert it into a data structure you can work with.
If you’d like to find out more about how JSON works, please visit the JSON website.
Fetching JSON from a Remote API
In the following examples, we’ll use the fantastic icanhazdadjoke API. As you can read in its documentation, making a GET request where the Accept header is set to application/json will see the API return a JSON payload.
Let’s start with a simple example:
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = () = > {
if (xhr.readyState === XMLHttpRequest.DONE) {
console.log(typeof xhr.responseText);
console.log(xhr.responseText);
}
};
xhr.open(‘GET’, ‘https://icanhazdadjoke.com/’, true);
xhr.setRequestHeader(‘Accept’, ‘application/json’);
xhr.send(null);

As we can see, the server returned us a string. We’ll need to parse this into a JavaScript object before we can loop through its properties. We can do this with JSON.parse():
if (xhr.readyState === XMLHttpRequest.DONE) {
const res = JSON.parse(xhr.responseText);
console.log(res);
};

Once we have our response as a JavaScript object, there are a number of methods we can use to loop through it.
Use a for…in Loop
A for…in loop iterates over all enumerable properties of an object:
const res = JSON.parse(xhr.responseText);

for (const key in res){
if(obj.hasOwnProperty(key)){
console.log(`${key} : ${res[key]}`)
}
}

Please be aware that for…of loops will iterate over the entire prototype chain, so here we’re using hasOwnProperty to ensure that the property belongs to our res object.
Use Object.entries, Object.values or Object.entries
An alternative approach to above is to use one of Object.keys(), Object.values() or Object.entries(). These will return an array which we can then iterate over.
Let’s take a look at using Object.entries. This returns an array of the key/value pairs of the object we pass it:
const res = JSON.parse(xhr.responseText);

Object.entries(res).forEach((entry) = > {
const [key, value] = entry;
console.log(`${key}: ${value}`);
});

Note that the const [key, value] = entry; syntax is an example of array destructuring that was introduced to the language in ES2015.
This is much more concise, avoids the aforementioned prototype problem, and is my preferred method of looping through a JSON response.
Using the Fetch API
While the method above using the XMLHttpRequest object works just fine, it can get unwieldy pretty quickly. We can do better.
The Fetch API is a Promise-based API, which enables a cleaner, more concise syntax and helps keep you out of callback hell. It provides a fetch() method defined on the window object, which you can use to perform requests. This method returns a Promise that you can use to retrieve the response of the request.
Let’s rewrite our previous example to use it:
(async () = > {
const res = await fetch(‘https://icanhazdadjoke.com/’, {
headers: { Accept: ‘application/json’ },
});
const json = await res.json();
Object.entries(json).forEach(([key, value]) = > {
console.log(`${key}: ${value}`);
});
})();

The Fetch API returns a response stream. This is not JSON, so instead of trying to call JSON.parse() on it, we’ll need to use its response.json() function. This returns a Promise that resolves with the result of parsing the response’s body text as JSON.
Dealing with an Array
As mentioned at the top of the article, an ordered list of values (aka an array), is valid JSON, so before we finish, let’s examine how to deal with such a response.
For the final example, we’ll use GitHub’s REST API to get a list of a user’s repositories:
(async () = > {
async function getRepos(username) {
const url = `https://api.github.com/users/${username}/repos`;

const response = await fetch(url);
const repositories = await response.json();

return repositories;
}

const repos = await getRepos(‘jameshibbard’);
console.log(repos);
})();

As you can see, the API has returned an array of objects. To access each of the individual objects, we can use a regular forEach method:
repos.forEach((repo) = > {
console.log(`{$repo.name} has ${repo.stargazers_count} stars`);
});

Alternatively, you can of course use any of the methods discussed above to loop through all of the object’s properties and log them to the console:
repos.forEach((repo) = > {
Object.entries(repo).forEach(([key, value]) = > {
console.log(`${key}: ${value}`);
});
});

Conclusion
In this quick tip, we’ve looked at what JSON is. I’ve demonstrated how to parse a JSON response from a server into a native data structure (such as an array or an object), and how to loop through such a structure, so as to access the data it contains.
If you’re having trouble with anything presented in this article, why not stop by SitePoint’s Forums, where there are plenty of friendly people to help you out.

How to make (passive) income with different services as a freelance web developer?

Hi, my question might sound easy on first thought, but quite complex on second thought:How do you make money as a freelance web developer?Well, sounds weird, I know. But hear me out:I´m a fullstack web developer who knows how to host and develop great websites.Recently I started working as a freelance web developer besides my fulltime job. Yey!I have the technical knowledge I need for that profession, but I don´t have the needed “Business Knowledge” yet. At first, I just thought “Well, people pay me for building a website once and that´s it.” But recently I found out about the opportunity of becoming a reseller host. I also know a lot about SEO and SEA. So why not sell those services as well?Goal: I want to build successfull websites and make some passive income where possible.Of course my goal is not to rip my clients off or anything like that.This would be potential services I could sell:Build a technical framework (i use Processwire with some manual adjustments) on which I base my freelance projects on. this saves a lot of time during the development because I don´t have to start from scratchEarn money once by building the website. This is where most of the money is earned.Earn little money by maintenance for updating the website, monitoring the SEO keywords by GoogleSearchConsole and adjusting keywords. E.g. I could charge 1-2 hours of maintenance each quater of the year.Earn passive income by hosting the website as a reseller host. I would usually charge a customer around 10€ to 12.50€ (equals 12$ to 15$) per month for hosting their website. this would generate my some passive income. It´s not much, but its a low hanging fruit and usually hosting contracts last quite long and require little effort. It´s beneficial for me (passive income) and the customer (I save time because I always have the same hoster)I would be happy to hear your thoughts on this topic, how do you make money as a Web Developer? only with Service #2 or also the others?Here are my questions:How much would you charge for the hosting? My reseller server costs me 10€ per month, each new project costs me 2.5€. If I would have 10 clients, the server would cost me 10€ + 25€ per month.How much hours of maintenance do you usually sell your customers? are they interested in this service? do they think seo adjustments and seo monitoring is necessary?Are there more services which you sell your customers?Which customers might need such “all in one” (consulting, development, online marketing and hosting) solutions? small business owners, right?are there any other ways for passive income?I would love to hear your answers, all the best from Austria!

Best Affiliate WooCommerce Plugins Compared

WooCommerce and WordPress are, together, a powerful and winning combination for online commerce. Together they run 37% of eCommerce business online. Leveraging these two is the perfect combination for selling physical products, digital goods, and services online.  But having the most awesome WooCommerce storefront and the best products is just a tiny part of what…

Best WordPress and WooCommerce Review Plugins

Do you want to add customer reviews on your website? Reviews are the best free advertising for your business and your products.  they bring traffic and make customers spend more time engaging with your website content. they give credibility to your products and inspire trust among visitors. they are social proof that your products are reliable. …

50+ Best Infographic Templates (Word, PowerPoint & Illustrator) 2021

An infographic can give you a way to represent information in a graphic format, designed to make it more understandable, relatable, and engaging. But they can be tricky to make! We’ve gathered together a collection of stunning infographic templates, to get you started quickly (whether you’re using Word, PowerPoint, or Illustrator!) Infographics usually require icons,…

17 Best WordPress Star Rating Plugins

Star ratings are used by websites to review all kinds of products and services. You can use them to rate pretty much anything your users are interested in: a movie, the food in a restaurant, the quality of service provided by a mechanic, etc. One of the reasons star ratings are so popular is that…