需求:
在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('\n识别结果:')
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}]