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.

Did you like this?
Tip admin with Cryptocurrency

Donate Bitcoin to admin

Scan to Donate Bitcoin to admin
Scan the QR code or copy the address below into your wallet to send some bitcoin:

Donate Bitcoin Cash to admin

Scan to Donate Bitcoin Cash to admin
Scan the QR code or copy the address below into your wallet to send bitcoin:

Donate Ethereum to admin

Scan to Donate Ethereum to admin
Scan the QR code or copy the address below into your wallet to send some Ether:

Donate Litecoin to admin

Scan to Donate Litecoin to admin
Scan the QR code or copy the address below into your wallet to send some Litecoin:

Donate Monero to admin

Scan to Donate Monero to admin
Scan the QR code or copy the address below into your wallet to send some Monero:

Donate ZCash to admin

Scan to Donate ZCash to admin
Scan the QR code or copy the address below into your wallet to send some ZCash:

Leave a Reply