首页 > Web开发 > 详细

json模块应用及数据查询

时间:2017-01-18 14:17:48      阅读:222      评论:0      收藏:0      [点我收藏+]

Json序列化对象供其他语言读写


JavaScript Object Notation

Json是被设计为跨语言使用的

Json是文本格式

Json必须使用unicode编码,默认utf-8方式存储

In [1]: import json

In [2]: d = {}

In [3]: d[‘a‘] = ‘a‘

In [4]: d[‘b‘] = 255

In [5]: d[‘c‘] = 255

In [6]: d[‘c‘] = (‘c1‘,‘c2‘)

In [7]: d[‘d‘] = True

In [8]: d[‘e‘] = None 

In [9]: with open(‘/tmp/d.json‘, mode = ‘w‘) as fd:
   ...:     json.dump(d,fd)
   ...:     

In [10]: cat /tmp/d.json
{"a": "a", "c": ["c1", "c2"], "b": 255, "e": null, "d": true}
In [11]: with open(‘/tmp/d.json‘) as fd:
    ...:     d1 = json.load(fd)
    ...:     

In [12]: d1
Out[12]: {u‘a‘: u‘a‘, u‘b‘: 255, u‘c‘: [u‘c1‘, u‘c2‘], u‘d‘: True, u‘e‘: None}

In [13]: type(d1)
Out[13]: dict

In [14]: d1[‘a‘]
Out[14]: u‘a‘

In [15]: type(d1[‘a‘])
Out[15]: unicode


In [2]: import sys

In [4]: from hostinfo.models import *

In [5]: Host.objects.all()#host=‘133’ 的太多了,报错
Out[5]: [<Host: 133>, <Host: 133>, <Host: 133>, <Host: 133>, <Host: 133>, <Host: 133>, <Host: 133>]

In [6]: Host.objects.get(hostname=‘133‘)
---------------------------------------------------------------------------
MultipleObjectsReturned       

#删除host=‘133’,只保留一个
In [9]: Host.objects.get(hostname=‘133‘)  
Out[9]: <Host: 133>

In [10]: Host.objects.get(hostname=‘134‘)
---------------------------------------------------------------------------
DoesNotExist                              Traceback (most recent call last)
<ipython-input-10-c6dd25e0bd04> in <module>()
In [11]: host = Host.objects.get(hostname=‘133‘)

In [12]: host.ip
Out[12]: u‘112.65.140.133‘

In [13]: host.hostname
Out[13]: u‘133‘

In [14]: host.ip = ‘112.65.140.132‘

In [15]: host.save()
#网页打开django页面可以看到系统意境变成了host=132,数据库更新成功。


本文出自 “梅花香自苦寒来!” 博客,请务必保留此出处http://daixuan.blog.51cto.com/5426657/1892822

json模块应用及数据查询

原文:http://daixuan.blog.51cto.com/5426657/1892822

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!