JSON Master : In-depth JSON tutorial for Beginners

栏目: IT技术 · 发布时间: 4年前

内容简介:JSON stands for JavaScript Object Notation. After writing this

JSON stands for JavaScript Object Notation. After writing this previous post on JSON , I’ve been receiving a lot of queries about how to parse different JSON structures and how to create JSON. So I’m writing this post to make JSON understandable for everyone. Let’s get started!

Update: This article is still relevant in 2020

JSON Master : In-depth JSON tutorial for Beginners

What is JSON?

JSON is a data exchange format. Let’s make it simple – JSON is a format in which data is sent or received so that it’s easy to read the data.

Can you give me one more example of data exchange format?

XML is another example of data exchange format. XML was widely used before JSON gained popularity. XML is used even today but JSON kicks XML’s ass any day :grinning:

Show me a practical example that uses JSON?

JSON is used everywhere. One simple example – Youtube API. If I want to pull trending videos in US then I can call youtube API which gives response in JSON format which looks like image below.

JSON Master : In-depth JSON tutorial for Beginners

Explore a wide list of JSON APIs here – Public JSON API list

Understanding JSON (Read this clearly)

Now that you know how JSON looks and its practical use cases, Let’s try to understand the structure of JSON.

JSON is built with just 2 data types – Object/Dictionary and Array .

Any valid JSON is always a Key-value pair object (dictionary) or an Array or a combination of both.

The one line just above this is all you need to master JSON. Most of them fail to understand this in the beginning.

Object

An object is a set of key-value pairs. An object begins with { and ends with } . Key-value pairs are separated by a comma.

Object is realized as different data types in different languages.

  • Dictionary in Python, VBA, VB.Net etc.
  • Associative array in PHP
  • Object in Javascript
  • Hash tables, key-value pairs etc

JSON Master : In-depth JSON tutorial for Beginners

Its basically a collection of keys and values. Here’s an example below.

{
    name: "Coding is Love",
    url: "https://codingislove.com"
}

An Object’s keys should always be a string in JSON. So it should be wrapped in quotes. Although regular object’s keys need not be wrapped in strings as shown in example above. So Object in JSON looks like this –

{
    "name": "Coding is Love",
    "url": "https://codingislove.com"
}

An Object’s values are usually accessed by specifying its property/keys’s name. Example in Javascript :

var siteData = {
name: "Coding is Love",
url : "https://codingislove.com"
}
console.log(siteData.name)        //logs "Coding is Love"
console.log(siteData.url)        //logs "https://codingislove.com"
console.log(siteData["name"])    //logs "Coding is Love"

It is accessed the same way in most programming languages. The syntax might change a bit but the basic concept remains the same. Access Values using it’s Key.

Note: Dictionaries in VBA can be accessed using siteData("name")

Array

An Array is a collection of values separated by comma. It starts with [ and ends with ]

Example :

["Name 1","Name 2","Name 3","Name 4"]

JSON Master : In-depth JSON tutorial for Beginners Array values are accessed by specifying Index. Array index start with 0.

var namesList = ["Name 1","Name 2","Name 3","Name 4"];
console.log(namesList[0]) //Logs "Name 1"
console.log(namesList[3]) //Logs "Name 4"

Note: If you are usingVBA-JSON in Excel VBA then it converts arrays into collections whose index start with 1 and can be accessed like this – namesList(1)

JSON Examples

If you understand Objects and arrays then JSON is very simple. Let’s see few possible ways in which JSON can be built.

JSON with Object

{
    "name": "Coding is Love",
    "url": "https://codingislove.com",
    "email": "<a href="/cdn-cgi/l/email-protection" data-cfemail="58393c353136183b373c31363f312b34372e3d763b3735">[email protected]</a>",
    "job": "Writing awesome content",
    "phone": 1234567890
}

JSON with Array

[1,2,3,4,5,6,7]

JSON with Array of objects

[
  {
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
  },
  {
    "userId": 1,
    "id": 2,
    "title": "qui est esse",
    "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
  }
]

Object inside an object

{
    "id": 1,
    "name": "Leanne Graham",
    "username": "Bret",
    "email": "<a href="/cdn-cgi/l/email-protection" data-cfemail="2b784245484e594e6b4a5b59424705494251">[email protected]</a>",
    "address": {
        "street": "Kulas Light",
        "suite": "Apt. 556",
        "city": "Gwenborough",
        "zipcode": "92998-3874",
        "geo": {
            "lat": "-37.3159",
            "lng": "81.1496"
        }
    }
}

Array inside object

{
    "id": 1,
    "profile": {
        "name": "John Doe",
        "Photos": ["url1", "url2"]
    }
}

So, Basically we can dump objects, arrays inside each other in any way we want and build a valid JSON as long as we follow the rules of Array and Object.

Parse JSON in different Languages

Few languages have built-in support for JSON and few don’t. Let’s see how to Build JSON and parse JSON in few languages.

Javascript

Javascript has built-in methods :

  1. JSON.Stringify(JSON Object) – Converts JSON Object to string. Usually used when sending data to server.
    var mydata = {name:"Coding is Love",score:25};
    var JsonString = JSON.Stringify(mydata);
    //post JsonString to server
  2. JSON.Parse(JSON String) – Converts JSON string into object which can be used to access the data. It is usually used when data is received from external source and parse data in it.
    var mydata = get JSON from your external source
    //lets say we are pulling the data that we posted from previous example.
    parsedObject = JSON.parse(mydata)
    alert(parsedObject.score) //alerts 25

Similar methods to parse and stringify JSON exist in most languages.

Python

Python has built-in JSON Encoder and Decoder. Documentation here – https://docs.python.org/2/library/json.html

import json
json.loads(JSON String)
json.dumps(Dictionary)

PHP

PHP also has built-in methods for parsing JSON. Documentation here – http://php.net/manual/en/book.json.php

json_decode(JSON string)
json_encode(Associative array)

VBA

There’s an in-detail post here –Parse JSON in Excel

Ruby

There’s a ruby gem here – https://github.com/flori/json

require 'json'
JSON.parse(string)
JSON.generate(object)

Wrapping up

If you read this post completely then I’m sure you’ve understood JSON! Now, Try using it in real life.

Need some learning project? Let’s say you want to build a custom website which shows only a particular set of youtube videos. Hit the youtube API, parse the JSON and become a JSON master!

If you have any questions or feedback, comment below.


以上所述就是小编给大家介绍的《JSON Master : In-depth JSON tutorial for Beginners》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

JavaScript实战手册

JavaScript实战手册

David Sawyer McFarland / 李强 / 机械工业出版社 / 2009 / 89.00元

在《JavaScript实战手册》中,畅销书作者David McFarland教你如何以高级的方式使用JavaScript,即便你只有很少或者没有编程经验。一旦掌握了这种语言的结构和术语,你将学习如何使用高级的JavaScript工具来快速为站点添加有用的交互,而不是一切从头开始编写脚本。和其他的Missing Manuals图书不同,《JavaScript实战手册》清楚、精炼,手把手地讲解。 ......一起来看看 《JavaScript实战手册》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

html转js在线工具
html转js在线工具

html转js在线工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具