python_json经常使用的方法

1. 什么是JSON?json

JSON 能够将 JavaScript 对象中表示的一组数据转换为字符串,而后就能够在函数之间轻松地传递这个字符串,或者在异步应用程序中将字符串从 Web 客户机传递给服务器端程序.数组

2. JSON语法服务器

    • 数据在键值对中
    • 数据由逗号分隔
    • 花括号保存对象
    • 方括号保存数组

3. json经常使用的方法异步

  • JSON到字典转化: ret_dict = json.loads(json_str)
  • 字典到JSON转化: json_str = json.dumps(dict)

4. 示例函数

# -*- coding: utf-8 -*-
import json

json_content = '{"name":"test", "type":{"name":"seq", "parameter":["1", "2"]}}'

print u"JSON到字典转化(方法一):"
l = eval(json_content)
print l
print l.keys()
print l["name"]
print l["type"]["name"]
print l["type"]["parameter"][1]

print u"JSON到字典转化(方法二):"
s = json.loads(json_content)
print s
print s.keys()
print s["name"]
print s["type"]["name"]
print s["type"]["parameter"][1]


dict_content = {"name":"test", "type":{"name":"seq", "parameter":["1", "2"]}}

print u"字典到JSON"
s = json.dumps(dict_content)
print s
try:
    print s.keys() 
except AttributeError:
    print u"对象不是字典!"

备注:     1. json对应的内容是符合json格式的字符串spa

相关文章
相关标签/搜索