JSON Overview and Tutorial 864
Introduction
This JSON overview tutorial will provide examples on how to easily create JSON objects. JSON objects are designed to help package information so it is readable by both humans and computers. It can also serve as an exchange between browsers and servers as well as APIs between various programming languages. A JSON files use the .json
extension and a data interchange file than can be read by most programming languages. This includes JavaScript when executing the fs.readFile()
method in Node.JS or jQuery’s jQuery.getJSON()
method in front-end JavaScript operating in a browser.
A Brief Overview of JSON
A JavaScript Object Notation, most commonly referred to a JSON object, is more accurately described as a data type or file format than a programming “language”. JSON was derived from JavaScript by Douglas Crockford in 2001 to provide a stateless protocol for exchanging data between servers and APIs. JSON supports a wide variety of data types that includes strings, integers and name-value pair objects.
Using JSON in a JavaScript or HTML file
JSON objects are essentially the same a JavaScript object literals, with the one difference being that JSON object fields must be enclosed in double-quotes.
It was designed and created with JavaScript in mind, so the best way to use JSON (on the front end) will either be within in the HTML file itself, or in a JavaScript (.js
) file. The following example shows how you can use the HTML <script>
tag to create a JSON object:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
NOTE: The JSON Standard specifies that you use double quotes ("
) when declaring JSON keys or values.
How to use JSON Objects in Other Languages
Most of the modern-day programming languages have native JSON support, or at least builtin libraries used to parse, iterate and access JSON fields and the respective data.
How to use JSON Objects in Python
The following Python code demonstrates how to declare a JSON string and convert it into a JSON-compliant dict
object:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | # import the json library import json # declare a JSON string some_str = '{"ObjectRocket": "Articles", "Hello": "World", "Integers": [12345, 42, 98765]}' # use the loads() method to create an object from str json_obj = json.loads(some_str) print ("JSON object type:", type(json_obj)) print ("JSON object:", json_obj, "n") # use the dumps() method to create a string from the object print (json.dumps(json_obj, indent=4), "n") # the following loads() call will return a JSONDecodeError print (json.loads("{this JSON object has bad syntax")) |
When executed using the python3
command, the above code should display the following results in a terminal or command-prompt window:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | JSON object type: <class 'dict'="'dict'"> JSON object: {'ObjectRocket': 'Articles', 'Hello': 'World', 'Integers': [12345, 42, 98765]} { "ObjectRocket": "Articles", "Hello": "World", "Integers": [ 12345, 42, 98765 ] } Traceback (most recent call last): File "json_example.py", line 19, in <module> print (json.loads("{this JSON object has bad syntax")) File "/usr/lib/python3.6/json/__init__.py", line 354, in loads return _default_decoder.decode(s) File "/usr/lib/python3.6/json/decoder.py", line 339, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/lib/python3.6/json/decoder.py", line 355, in raw_decode obj, end = self.scan_once(s, idx) json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1) |
As shown above, and in the below screenshot, Python will return a json.decoder.JSONDecodeError
exception if there is an attempt to pass an invalid JSON string to the json.loads()
method.
How to use JSON Objects in PHP
PHP has two functions called json_decode
and json_encode
. These allow for easy conversion of JSON objects into strings, and vice-versa. The following is an example of how to decode a PHP string into a JSON object and then how to convert it back into a string:
1 2 3 4 5 6 7 8 9 10 11 | // declare and JSON encode string $str = '{"ObjectRocket": "Articles"}'; $jsonObj = json_decode($str); // use PHP's var_dump() function to parse the JSON key-value pair var_dump($jsonObj); // encode a JSON string and echo the result $jsonStr = json_encode($jsonObj); echo " JSON string: ". json_encode($str); |
When the above PHP code is run in a browser it should display the following results on the web page:
1 2 | object(stdClass)#1 (1) { ["ObjectRocket"]=> string(8) "Articles" } JSON string: "{"ObjectRocket": "Articles"}" |
Conclusion
This JSON overview tutorial gave examples of how to create JSON objects. The article provided a brief overview of what JSON is and explained how to use JSON in a JavaScript or HTML file. The tutorial also explained how to use JSON objects in other languages, specifically Python and PHP. Remember that the JSON Standard specifies that double quotes ("
) must be used when declaring JSON keys or values.
Pilot the ObjectRocket Platform Free!
Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.
Get Started