Creating JSON with «bare hænds»

When you write software you mostly use contemporain software when each object has a method like «toJSON» or «parseAsJSON». But sometimes it happens that you need to create JSON string using an obsolete software version.
So you need to use some recursive function call or apply some graph theory knowledge.


It seems that to create a JSON string is simple, especially when you do not work with deeply linked objects but operate with data structures like a dataset returned from database.
But sometimes you can get come errors if you just create the string like {"param_name":"param_value_received_from_server_1"} because not each param_value_received_from_server_1 is suitable for JSON especially if it contains some symbols having special role in JSON standard.

First of all you shoud reat the information at http://json.org/

There you can read about all allowed values and symbols.
If you string contains quotes or slashes you must add backslash before them like it is shown in the table below

" \"
\ \"
/ \"

After that you can create some valid JSON but only when your original strings do not contain some special character.

The symbols with ASCII code less than 32 is not suitable in your string.
The table below shows the way you should transform the symbols with code less than 32

0 \u0000
1 \u0001
2 \u0002
3 \u0003
4 \u0004
5 \u0005
6 \u0006
7 \u0007
8 \b
9 \t
10 \n
11 \u000b
12 \f
13 \r
14 \u000e
15 \u000f
16 \u0010
17 \u0011
18 \u0012
19 \u0013
20 \u0014
21 \u0015
22 \u0016
23 \u0017
24 \u0018
25 \u0019
26 \u001a
27 \u001b
28 \u001c
29 \u001d
30 \u001e
31 \u001f

It should be noticed each symbol can be presented in «\uXXXX» form where XXXX is just its code.
For example in JavaScript JSON.parse(‘\"\u0052\"’) will correcly parse the letter of S.


Поделиться:
1 Звезда2 Звезды3 Звезды4 Звезды5 Звезд (Пока оценок нет)
Загрузка...

Creating JSON with «bare hænds»: 2 комментария

  1. > If you string contains quotes or slashes
    Look at the table, please. Those are not the quotes that you expected, are those? Use Crayon button at the editor top menu to paste code to the article.
    And don’t forget to insert “read mmore” tag.

Добавить комментарий

Ваш e-mail не будет опубликован.

*