How to use JSON in JavaScript

Javascript JSON

Because JSON is so simple

JSON is the most popular exchange format because JSON is easy to read (more readable than XML, which is being replaced more and more by JSON). JSON is simple, fast and generates little overhead.

Austen Jane Sanditon Pride and Prejudice Emma {"author": "Austen" "firstname": "Jane" "books": ["Sanditon", "Pride and Prejudice", "Emma"]} let info = JSON.parse (data) ; info.books [1] // Pride and Prejudice

Anyone who has to deal with XML tags, namespaces, attributes and schemas will experience a complicated and time-consuming process. JSON, on the other hand, gives preference to the relevant data.

For example, the configuration of the Bracket (bracket.json) code editor - as the name extension suggests - is in JSON format and Twitter from version 1.1 onwards no longer uses JSON on XML.

JSON and Javascript objects

A JSON object is a collection of key-value pairs. But even though JSON objects look almost like simple Javascript objects, there are differences.

JSON keys are strings in double quotation marks. The key is on the left, the value on the right.

JSON object
{"color": "yellow"} | | | + - value + - key
Javascript object
let colors = {color: "yellow"}

Javascript objects and JSON objects look very similar: the double quotation marks around the key differentiate the notation.

Special characters and spaces for JSON keys are entirely correct, but they make parsing complicated. So "fill-color" or "fill color" would be valid keys, but if the JSON object is parsed into a Javascript object, hyphens and spaces are not part of the repertoire of valid characters for a Javascript variable name.

JSON values

{"boolean": true, "null": null, "number": 123}

Boolean, numeric values, and zero are not in single quotes.

Simple JSON data

"Name": "Marsalla"

JSON objects contain multiple name / value pairs. This is where the dot notation comes into play: object.spies. There is no guarantee that Javascript will save the elements of an object in order.

"Name": "Marsalla", "species": "Cat"

JSON arrays are enclosed in square brackets like normal Javascript arrays and access is via the index like an array.

let pets = [{"name": "Marsalla", "species": "cat"}, {"name": "Theocrates", "species": "Fox Terrier"}, {"name": "Wallis", " species ":" Friesland "}]; pets [1] .species + "" + pets [1] .name;

We always need the array notation when JSON keys use special characters or spaces and are not valid Javascript variable names.

JSON parse ()

JSON has to be translated - parsed - into Javascript. JSON can be used with Javascript eval be parsed, but you keep your hands off that today, because eval is considered undesirable, does not work in strict mode and is banned from Javascript. JSON with jQuery frees you from queries and checks on very, very old browsers.

The modern alternative is JSON.parse (), that is more secure than eval and is supported by all modern browsers from IE8 onwards.

{"author": "Schuiten und Peters", "book": {"title": "Bruesel", "published": "1992", "image": "https://www.mediaevent.de/javascript/img /bruesel.jpg "}}

Access to the data is very easy. First parse with JSON.parse () - and in obj a javascript object with obj.author or obj.book.published ready.

let comic = '{"author": "Schuiten und Peters", "book": {"title": "Bruesel", "published": "1992", "image": "https://www.mediaevent.de /javascript/img/bruesel.jpg "}} '; let obj = JSON.parse (comic); document.querySelector ("# simplejson"). innerHTML = obj.author + "

" + obj.book.title + "

<comic> <author>Peters und Schuiten</author> <book> <title>Bruesel</title> <published>1992</published> <image>https://www.mediaevent.de/javascript/img/bruesel.jpg</image> </book> </comic>

" + obj.book.published + "" + " "; With XML, even such a small object would come with a torrent of overhead. Parsing would be much more complicated and error-prone.JSON.stringify ()

is the reverse of

parse ()

and converts a Javascript JSON object to a string.

<div id="symtable"></div>

Reload content with JSON and Ajax A perfect symbiosis: Javascript JSON with Ajax loads data from the server without reloading the page and without the assistance of a server-side application (e.g. PHP). JSON data is usually generated by a server-side application, but a simple JSON file is sufficient for reloading content into the website.:

As soon as the user scrolls the page, the lines are reloaded via fetch (). This keeps the loading time for a long table short and does not even lead to a data transfer if the user is not interested in the further content.

The other lines are in a text file

symbols.json <= (window.innerheight="" ||="" html.clientheight)="" &&="" rect.right=""><= (window.innerwidth="" ||="" html.clientwidth)="" );="" }="" function="" appenddata="" (data)="" {="" console.log="" ("appenddata");="" const="" container="document.querySelector("#symtable");" for="" (let="" i="0;" i<data.length;="" i++)="" {="" const="" div="document.createElement" ("div");="" div.innerhtml="<span>" +="" data[i].name="" +="" "</span><span>"="" +="" data[i].symbol1="" +="" "</span><span>"="" +="" data[i].desc="" +="" "</span>";="" container.appendchild="" (div);="" }="" }="" window.onscroll="function" ()="" {="" if="" (isinviewport="" (document.getelementbyid('onebefore'))="" )="" {="" window.onscroll="null;" fetch="" ("symbols.json").then="" (function="" (response)="" {="" return="" response.json();="" }).then="" (function="" (data)="" {="" appenddata="" (data);="" }).catch="" (function="" (error)="" {="" console.log="" ("fehler:="" "="" +="" error);="" });="" }="" }="">

[{"name": "Icon, scissors", "symbol1": "✂", "desc": "Open scissors"}, {"name": "Icon, arrow", "symbol1": "✆", " desc ":" Telephone receiver, cord forms a circle "}, {" name ":" Icon, airplane "," symbol1 ":" ✈ "," desc ":" airplane "},]

The script fires when the table becomes visible while scrolling - comes into the viewport - and then logs off the scroll event again. The script opens the file with the JSON object via Javascript fetch () and parses the data (fetch: the elegant little variant of Ajax requests).

function isInViewport (element) {const rect = element.getBoundingClientRect (); const html = document.documentElement; return (rect.top> = 0 && rect.left> = 0 && rect.bottom

With node.js, Javascript can save JSON directly, otherwise the script for saving JSON must be set to PHP.

Iterate over a JSON object

JSON has a rudimentary iteration built in, so all properties and values ​​are easy to access.

const terms = {"float with the current": "float with the current", "on a high level"} for (let prop in terms) {console.log (prop, terms [prop]) ; }

for-in iteration for Javascript objects

More elegant: array.map takes values ​​from a JSON array into a new array. Here array.map reads all the values ​​of lightroom into a simple array of keywords:

const json = [{"filename": "pipette.svg", "path": "svg \ / icon", "rating": "4", "urgency": "0", "lightroom": "Computer, Icon "}, {" filename ":" haushalt-kaffemaschine.svg "," path ":" svg \ / icon "," rating ":" 0 "," urgency ":" 0 "," lightroom ":" Icon, Household "}…]; let bags = json.map (a => a.lightroom); console.log (bags);

By the way: IE11 doesn't play along with the arrow function!

It is not that easy for Javascript to get value and key at the same time - the key-value pair - if access is to run via the index. const index = 3; const key = Object.keys (terms) [index]; value = terms [key]; console.log (key, value);JSON and PHP

JSON is also used to communicate with PHP applications on the server. PHP can evaluate JSON directly: PHP

json_decode

converts a JSON string into a PHP variable.

Ajax2 can easily upload multiple files to the server. JSON-LD for metadataIn the end, JSON is also used for rich snippets - additional, invisible markup for metadata in HTML pages. The JSON-LD Javascript notation is embedded in the head or body element of the page like a script tag.

<script type="application/ld+json"> { "@context": "http://schema.org", "@type": "WebPage", "headline": "7 Tipps für Fotos mit Blitz bei Sonnenschein und Gegenlicht", "datePublished": "2013-04-05", "dateModified": "2018-01-01", "lastReviewed": "2018-03-13", "potentialAction": { "@type": "SearchAction", "target": "https://ivent.de/webscout/search.php?query={search_term}", "query-input": "required name=search_term" }, "image" : [ "https://ivent.de/assets/foto-mit-blitz/lead.jpg" ] } </script>

That has compared to the scattered HTML attributes like