Welcome, guest | Sign In | My Account | Store | Cart

This JSON parser works well with stringified Python list or dictionary. It is from json.org javacript json parser with small modification.

Python, 267 lines
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
this is ajax.html
------------------------------------------------
<html>
<head>
<title>simple ajax json example</title>
<script language="JavaScript">
    //json parser
    //from json.org with small modification
    var cur_str_chr;
    function json_parse(text) {
        var at = 0;
        var ch = ' ';

        function error(m) {
            throw {
                name: 'JSONError',
                message: m,
                at: at - 1,
                text: text
            };
        }

        function next() {
            ch = text.charAt(at);
            at += 1;
            return ch;
        }

        function white() {
            while (ch !== '' && ch <= ' ') {
                next();
            }
        }

        function str() {
            var i, s = '', t, u;

            if (ch == '\'' || ch == '"') { //change " to ' for python
                cur_str_chr = ch;
outer:          while (next()) {
                    if (ch == cur_str_chr) {
                        next();
                        return s;
                    } else if (ch == '\\') {
                        switch (next()) {
                        case 'b':
                            s += '\b';
                            break;
                        case 'f':
                            s += '\f';
                            break;
                        case 'n':
                            s += '\n';
                            break;
                        case 'r':
                            s += '\r';
                            break;
                        case 't':
                            s += '\t';
                            break;
                        case 'u':
                            u = 0;
                            for (i = 0; i < 4; i += 1) {
                                t = parseInt(next(), 16);
                                if (!isFinite(t)) {
                                    break outer;
                                }
                                u = u * 16 + t;
                            }
                            s += String.fromCharCode(u);
                            break;
                        default:
                            s += ch;
                        }
                    } else {
                        s += ch;
                    }
                }
            }
            error("Bad string");
        }

        function arr() {
            var a = [];

            if (ch == '[') {
                next();
                white();
                if (ch == ']') {
                    next();
                    return a;
                }
                while (ch) {
                    a.push(val());
                    white();
                    if (ch == ']') {
                        next();
                        return a;
                    } else if (ch != ',') {
                        break;
                    }
                    next();
                    white();
                }
            }
            error("Bad array");
        }

        function obj() {
            var k, o = {};

            if (ch == '{') {
                next();
                white();
                if (ch == '}') {
                    next();
                    return o;
                }
                while (ch) {
                    k = str();
                    white();
                    if (ch != ':') {
                        break;
                    }
                    next();
                    o[k] = val();
                    white();
                    if (ch == '}') {
                        next();
                        return o;
                    } else if (ch != ',') {
                        break;
                    }
                    next();
                    white();
                }
            }
            error("Bad object");
        }

        function num() {
            var n = '', v;
            if (ch == '-') {
                n = '-';
                next();
            }
            while (ch >= '0' && ch <= '9') {
                n += ch;
                next();
            }
            if (ch == '.') {
                n += '.';
                while (next() && ch >= '0' && ch <= '9') {
                    n += ch;
                }
            }
            if (ch == 'e' || ch == 'E') {
                n += 'e';
                next();
                if (ch == '-' || ch == '+') {
                    n += ch;
                    next();
                }
                while (ch >= '0' && ch <= '9') {
                    n += ch;
                    next();
                }
            }
            if (ch == 'L')next();//for python long
            v = +n;
            if (!isFinite(v)) {
                error("Bad number");
            } else {
                return v;
            }
        }

        function word() {
            switch (ch) {
                case 't':
                    if (next() == 'r' && next() == 'u' && next() == 'e') {
                        next();
                        return true;
                    }
                    break;
                case 'f':
                    if (next() == 'a' && next() == 'l' && next() == 's' &&
                            next() == 'e') {
                        next();
                        return false;
                    }
                    break;
                case 'n':
                    if (next() == 'u' && next() == 'l' && next() == 'l') {
                        next();
                        return null;
                    }
                    break;
            }
            error("Syntax error");
        }

        function val() {
            white();
            switch (ch) {
                case '{':
                    return obj();
                case '[':
                    return arr();
                case '\'':
                case '"':
                    return str();
                case '-':
                    return num();
                default:
                    return ch >= '0' && ch <= '9' ? num() : word();
            }
        }

        return val();
    }
    //end json parser

function loadurl(dest) { 
    xmlhttp = window.XMLHttpRequest?new XMLHttpRequest(): new ActiveXObject("Microsoft.XMLHTTP");
    xmlhttp.onreadystatechange = pop_table;
    xmlhttp.open("GET", dest);
    xmlhttp.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
    xmlhttp.send(null);
}
function pop_table() {
    if ((xmlhttp.readyState == 4) && (xmlhttp.status == 200)) {
        var json_data = json_parse(xmlhttp.responseText);
	var rows = document.getElementById("testtable").getElementsByTagName("tr");
	rows[0].childNodes[0].innerHTML = json_data[0]['one']
	rows[0].childNodes[1].innerHTML = json_data[0]['two']
	rows[0].childNodes[2].innerHTML = json_data[0]['three']
	for(i=0;i<rows[1].childNodes.length;i++)
		rows[1].childNodes[i].innerHTML = json_data[1][i]
	rows[2].childNodes[0].innerHTML = json_data[2]['title']
	rows[2].childNodes[2].innerHTML = json_data[2]['random']
    }
}
</script>
</head>
<body>
<div id="clickhere" onclick="loadurl('/cgi-bin/ajax.cgi')">click here</div>
<table id="testtable" border=1>
<tr><td>11</td><td>12</td><td>13</td></tr>
<tr><td>21</td><td>22</td><td>23</td></tr>
<tr><td>31</td><td>32</td><td>33</td></tr>
</table>
</body>
</html>
--------------------------------------------

This is /cgi-bin/ajax.cgi
--------------------------------------------
#!/bin/env python
import random
print "Content-type: text/html;charset=utf-8\r\n"
data =[]
data.append({"one":'Hello world',"two":12345678L,"three":3.1415926})
data.append(['to',"be","or",'not',"to",'be'])
data.append({'title':"that's the question",'random':random.randrange(0,1000000)})
print str(data)
----------------------------------------------

Put the first file ajax.html to your web directory. Put the second file ajax.cgi in your cgi-bin directory. The original parser use double quote '"' as string dilimiter. However python list and dictionary use single quote '\'' (unless there are single quote character in the stirng, then it will use double quote). The original parser doesn't handle long integer. This parser handle both double and sigle quote, as well as long integer. The pop_table function is just a silly example to show that you can access returned python list or dictionary easily. The last line of ajax.cgi could be just "print data", because print statement convert object to string implicitly. However if you use something other than CGI, you need to convert object to string explicitly.

Limitation: The returned list or dictionary can not have object type other than: list, dictionary, string, and number. Tuple should be converted to list. For number, there can not be complex number.

3 comments

Wensheng Wang (author) 18 years, 6 months ago  # | flag

a little fancier example. http://wswang.com/pytan/ajaxdemo

it display a random number in random background color, then fade in white.

It used "Fade Anything Technique" from http://www.axentric.com

Noah Spurrier 17 years, 8 months ago  # | flag

Need input and output. This is a nice example, but it would be cool if you included both input and output from the ajax handler. This one just does output.

Binod Suman 14 years, 10 months ago  # | flag

Very nice tutorial. I have also written one very basic and fundamental tutorial on Ajax with JSON.

http://binodsuman.blogspot.com/2009/05/ajax-and-json-example-how-to-use-json.html

Thanks,

Binod Suman http://binodsuman.blogspot.com

Created by Wensheng Wang on Mon, 3 Oct 2005 (PSF)
Python recipes (4591)
Wensheng Wang's recipes (5)

Required Modules

  • (none specified)

Other Information and Tasks