JSON Master : In-depth JSON tutorial for Beginners

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

内容简介: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》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

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

微商思维

微商思维

龚文祥、罗剑锋、触电会 / 金城出版社 / 2018-7 / 88.00元

微商不仅仅是一种继传统实体、电商之后的革命性新兴商业形态,更是一种能够写入中国商业史的思潮。龚文祥新著《微商思维》,从道的层面对广大微商人的商业实践智慧进行了高度浓缩与抽象总结,站在更高的视角解读微商背后的商业逻辑与本质。 本书前半部分,主要从本质、品牌、营销等几个方面,阐述了微商思维的内涵及应用场景,帮助读者了解并认识这种革命性的商业思维。 后半部分主要是触电会社群内部各位大咖的实操......一起来看看 《微商思维》 这本书的介绍吧!

SHA 加密
SHA 加密

SHA 加密工具

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具