[英]JSON from curl as a function parameter
我正在尝试使用curl的API,返回一个JSON:
response=$(curl -i --user api:$APIKey --data-binary @$target https://api.tinypng.com/shrink)
接下来,我尝试使用函数解析(简要)响应:
parseJson(){
result="$1"
result=($(echo $result | python -mjson.tool))
result=${result%\"*}
result=${result##*\"}
return $result
}
我这样称呼它: message=$(parseJson "$response" message)
。 仅供参考,回应是多行的。
但奇怪的事情发生了:python给了我No JSON object could be decoded
,但如果我回显$ result有一个很好的JSON字符串。 更奇怪的是,如果我在调用python之前回应它,看起来无论如何都会首先执行python。
有一些异步技巧吗? 为什么我不能将变量字符串传递给python?
任何帮助或更好的方法将不胜感激!
我认为No JSON Object could be decoded
, the response is on multiple lines
上是关键。 该错误通常从空字符串上的mjson.tools返回,而格式错误的JSON通常会返回更详细的内容。
JSON解析器不会超过第一个换行符(在引用字符串值之外)。 它可能会收到类似\\ r \\ n {“key”:“value”}并失败的内容。 如果由于某种原因响应是多行的,那么你应该解析出响应体(JSON)而不带前导或尾随\\ r \\ n的
您可以尝试HttpConnection而不是调用curl并直接在python中执行所有操作:
conn = httplib.HTTPConnection('www.a_url.com')
conn.request("GET", /index.html')
response = conn.getresponse()
status = response.status
if status != 200:
print 'ERROR'
sys.exit(1)
reason = response.reason
answer = response.read()
为了让json做到:
received_json = None
try:
json.loads(answer)
except:
print 'ERROR'
sys.exit(2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.