JSON in javascript, python, and php

I often got confused about JSON and JSON string. JSON is the code you write in your javascript script to represent an object, so the code is called JavaScript Object Notation.  But we can include the piece of code in a string, and the string is called JSON string. Why we need JSON string considering the fact that we can directly write a javascript object with JSON? Well, that is because we can easily transfer a javascript object between client and server by converting the object to a JSON string. If you do not encode the javascript into a  JSON string, you have to transfer the binary data of the javascript object, which is not convenient. You can refer to this post about transferring javascript objects over the network.

JSON encoding and decoding in javascript(reference)

encode a javascript object to a JSON string:

var str=JSON.stringify(obj);

decode a JSON string to a javascript object:

var obj=JSON.parse(str);

Store a json string to local storage:

localStorage.setItem(“aname”, JSON.stringify(obj));

retrieving a javascript object from local storage:

var obj=JSON.parse(localStorage.getItem(“aname”));

 

JSON Encoding and Decoding in python (reference)

encode a python object to a JSON string:

import json
str=json.dumps(obj);

decode a JSON string to a python object:

import json
obj=json.loads(str);

save a python object to a file:

import json
with open('obj.json', 'w') as f:
  json.dump(obj,f);

read a python object from a file:

import json
with open('obj.json', 'r') as f:
  obj=json.load(f);

JSON encoding and decoding in php(reference)

encode a php object to a JSON string:

$str=json_encode($obj);

 decode a JSON string to a php object:

$obj=json_decode($str);

We can see almost all programming languages provide functions or a library to encode and parse JSON strings. Converting a string to an object or vice verse is very simple, almost a line of code.

Leave a Reply