ssk’s posterous

ssk’s posterous

Oct 29 / 1:04am

pythonとperlとphpとas3とjavascriptでJSON « taichino.com

by ssk

python
2.6系だとJSONが標準で組み込まれてるらしいんですが、手元は2.5系なのでsimplejsonを使っています。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys, codecs
sys.stdout = codecs.getwriter('utf_8')(sys.stdout)
 
import simplejson
 
data = { 'items':[
  {'name':'iPhone',  'price':50000},
  {'name':'macbook', 'price':100000},
  {'name':"マクド",  'price':100},
]}
text = simplejson.dumps(data)  # encode
copy = simplejson.loads(text)  # decode
 
print "data = " + str(data)
print "text = " + text
print "copy = " + str(copy)
for item in copy['items']:
  print item["name"]

Filed under  //  json   python  

Comments (0)

Oct 25 / 9:27pm

arbiter's dream place in Utah: Python and MySQL technique - Render JSON ouput based on MySQLdb to MySQL

by ssk
Here is the code.
import MySQLdb
import simplejson as json
db = MySQLdb.connect(host='xxx', user='xx', passwd='xx', db='xxx')
cursor = db.cursor()
def getSQLJSON(hostName,dbName,id,pw,sql):
global db,cursor
resultArray =[]
cursor.execute(sql)
tableDescription = cursor.description
result = cursor.fetchall()
for e in result:
resultRaw ={}
columnIndex =0
for ee in e:
vcoulumnName = tableDescription [columnIndex][0]
resultRaw[coulumnName]=ee
columnIndex +=1
resultArray.append(resultRaw)
jsonResult = json.dumps(resultArray, separators=(',',':'))
return jsonResult

mysql の出力を JSON 形式へ?

Filed under  //  json   mysql   python  

Comments (0)