As an alternative to /opt/lampp/bin/php, to run a php…
February 23, 2018
Shell:验证json文件各式是否正确, Validate JSON from the command line on Linux, Format JSON with Python
现在以json为数据传输格式的RESTful接口非常流行。为调试这样的接口,一个常用的办法是使用curl命令:
curl http://somehost.com/some-restful-api
对于返回的json字符串,一般在服务端不加处理的情况下,都是没有任何’\t’和’\n’的。为了方便查看,在bash上可以简单地对它进行格式化:
curl http://somehost.com/some-restful-api | python -m json.tool
当然这要求机器上安装了python,其实也就是利用了json.tool这个程序。
一旦json文件格式不对,或者文件内容缺失或者其他问题,就会导致 python -m 命令无法格式化,正是利用这一点,我们可以做一个json的验证!
方法:
cat <json File> | python -m json.tool
或者
python -c "import json,sys; txt=sys.stdin.read(); json.loads(txt)"
实例:
#!/usr/bin/env bash cat just_code.json | python -m json.tool 1>/dev/null 2>/tmp/json_error error=$(cat /tmp/json_error) echo ${#error}-${error} if [ ${#error} -eq 0 ] then echo 'just_code.json is a valid file.' sudo rm -r /tmp/json_error else echo "just_code.json is a invalid file, error is : ${error}" fi
简单解释一下,
/dev/null :代表空设备文件
> :代表重定向到哪里,例如:echo “123” > /home/123.txt
1 :表示stdout标准输出,系统默认值是1,所以”>/dev/null”等同于”1>/dev/null”
2 :表示stderr标准错误
& :表示等同于的意思,2>&1,表示2的输出重定向等同于1
1>/dev/null 2>/tmp/json_error 的含义就是,正确的输入重定向到空设备/dev/null ,也就是不要输出任何正确内容,便准错误重定向到文件/tmp/json_error中
本文:Shell:验证json文件各式是否正确, Validate JSON from the command line on Linux