zoukankan      html  css  js  c++  java
  • 如何读写json数据?

    需求:
    在web应用中常用JSON(JavaScript ObjectNotation)格式传输数据,例如我们利用baidu语音识别服务器做语音识别,将本地音频数据post到baidu语音识别服务器,服务器响应为json字符串:
    {"corpus_no":"64444888973976730779908","err_msg":"success","err_no":0,"result":["你好,"],"sn":"4183597886765789977954455606"}
    在python中如何读写json数据?

    思路:
    使用标准库中的josn模块,其中的loads,dump函数可以完成对json数据的读写

    代码:

    import requests
    import json
    
    # 录音
    from record import Record
    record = Record(channels=1)
    audioData = record.record(2)
    
    # 获取token
    from secret import API_KEY,SECRET_KEY
    authurl =  'https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id={}&client_secret={}'.format(API_KEY,SECRET_KEY)
    response = requests.get(authurl)
    res = json.loads(response.content)  # 将json格式的字符串转化为一个python对象,得到一个字典
    token = res['access_token']  
    print(token)
    
    # 语音识别
    cuid = 'xxxxxxxxx'
    srvUrl = 'http://vop.baidu.com/server_api'+'?cuid=' + cuid +'&token=' + token
    httpHeader = {
        'Content-Type':'audio/wav; rate = 8000',
    }
    response = requests.post(srvUrl,headers=httpHeader,data=audioData)
    res = json.loads(response.content)
    text = res['result'][0]
    
    print('
    识别结果:')
    print(text)
    
    ========================================================
    
    In [153]: l = [1,2,'abc',{'name':'Bob','age':13}]
    
    In [154]: json.dumps(l)
    Out[154]: '[1, 2, "abc", {"name": "Bob", "age": 13}]'
    
    In [155]: d = {'a':None,'a':5,'c':'abc'}
    
    In [156]: json.dumps(d)
    Out[156]: '{"a": 5, "c": "abc"}'
    
    In [157]: d = {'b':None,'a':5,'c':'abc'}
    
    In [158]: json.dumps(d)  # None这里变为null
    Out[158]: '{"b": null, "a": 5, "c": "abc"}'
    
    In [159]: json.dumps(d,separators=[',',':'])   # 在网络传输中,去除键值之间的空格。
         ...:
         ...:
    Out[159]: '{"b":null,"a":5,"c":"abc"}'
    
    In [160]: json.dumps(d,sort_keys=True)  # 按键来进行排序
    Out[160]: '{"a": 5, "b": null, "c": "abc"}'
    
    In [162]: l2 = json.loads('[1, 2, "abc", {"name": "Bob", "age": 13}]')  # 将json字符串转化为python的对象。
    In [163]: l2
    Out[163]: [1, 2, 'abc', {'name': 'Bob', 'age': 13}]
    
    In [165]: with open('demo.json','w') as f:  # json.dump()方法,这个和dumps()功能一样,只是接收的参数对象为打开的文件对象。
         ...:     json.dump(l,f)
         ...:
    
    In [166]: cat demo.json
    [1, 2, "abc", {"name": "Bob", "age": 13}]
    
    In [173]: json.load(open('demo.json'))
    Out[173]: [1, 2, 'abc', {'name': 'Bob', 'age': 13}]
    
    
  • 相关阅读:
    数据结构八树和森林
    数据结构 七 二叉树的遍历
    python 的 encode 、decode、字节串、字符串
    TCP/IP
    pg 数据库操作
    nginx + lua 的 跳转命令
    lua string 下的函数
    lua 的匹配规则
    nginx的 ngx.var ngx.ctx ngx.req
    docker 网络模式 和 端口映射
  • 原文地址:https://www.cnblogs.com/Richardo-M-Q/p/13337584.html
Copyright © 2011-2022 走看看