来自json的查询mysql来自angularjs - Python

时间:2015-05-14 08:23:47

标签: python json angularjs

嗨大家我已经获得了json数据,这是我来自angularjs的json数据,有人可以帮我吗?我只是坚持下去了。谢谢。

{u'isChecked': {u'49871': False, u'49870': True, u'113634': False}}

然后在我的python中,我想在json数据中找到id时更新mysql

现在这里是我的更新代码,我想将它连接到我的json数据

   updatetable = """UPDATE table_x
                                 SET value = '1'
                                """
        db.session.execute(updatetable)
        db.session.commit()

1 个答案:

答案 0 :(得分:1)

这是一个解决方案

#!/usr/bin/env python

import platform
import sys
import urllib2
import simplejson as json

def update_table(id):
    sqlUpdateStr = "UPDATE table_x SET value = '1' where id="+id
    print "Executing update: " + sqlUpdateStr

def test_parse_json():
    print "Loading json ..."
    req = urllib2.Request("http://localhost/example.json")
    opener = urllib2.build_opener()
    f = opener.open(req)
    # json.load() will deserialize your JSON document and return a Python object.
    data = json.load(f)

    print data['isChecked']
    print ""

    for id in data['isChecked']:
        id_val = str2bool(data['isChecked'][id])
        if id_val == True:
            print "Found id for update: " + id
            update_table(id)
        else:
            print "Ignoring record with id=" + id

def str2bool(v):
    return v.lower() in ("yes", "true", "t", "1")

def main():
    test_parse_json()

    return


if __name__ == '__main__':
    main()

,example.json的内容是:

{
    "isChecked":{
        "49870":"true",
        "49871":"false",
        "113634":"false"
    }
}