简体   繁体   English

如何在bash中解析json或将curl输出传递给python脚本

[英]How to parse json in bash or pass curl output to python script

I'm looking to find some way to have pretty print of curl's output in json. 我正在寻找一种方法来在json中漂亮地显示curl的输出。 I wrote short python script for this purpose, but it won't work with pipe Also I don't want to use subprocesses and run curl from them: 我为此编写了简短的python脚本,但是它不适用于管道,而且我也不想使用子进程并从中运行curl:

So python: 所以python:

#!/usr/bin/python

import simplejson
from pprint import pprint
import sys
print pprint(simplejson.loads(sys.argv[1]))

And json information is: json信息是:

{"response": {"utilization": {"eic": [{"date": "2012.03.06", "usage": []}, {"date": "2012.03.07", "usage": [{"srvCode": "SVC302", "upload": 267547188, "api-calls": {"fileGetInfo": 30, "getUserStorageQuota": 0, "setUserStorageQuota": 0, "fileUploadFlashInit": 31, "getAPISessionUser": 0, "setFileAccessControl": 0, "fileGetPreviewUrl": 0, "fileStartMultipartUpload": 0, "getServiceQuota": 0, "fileGetPreviewUrlsForBunch": 10, "xcodingGetStreamUrl": 0, "getSessionTimeLimit": 0, "fileGetCoversUrlsForBunch": 27, "makePreviews": 0, "setServiceQuota": 0, "getAPISessionTrusted": 3, "getFileAccessControl": 0, "xcodingGetFormats": 0, "getQuotaNotificationEmail": 0, "fileGetDownloadUrl": 0, "xcodingGetStreamInfo": 0, "fileUploadDone": 30, "getLocalServiceUtilization": 9, "getServiceUtilization": 0, "fileDelete": 19, "setSessionTimeLimit": 0, "fileGetMultipartUploadUrl": 0, "fileUploadInit": 0, "extractFileMetadata": 30, "setQuotaNotificationEmail": 0}, "average-storage": 3801210959.4961309, "download": 0, "transcoding": 0}]}]}}}

Using json.tool from the shell to validate and pretty-print: 从外壳使用json.tool进行验证并进行漂亮打印:

$ echo '{"json":"obj"}' | python -mjson.tool
{
    "json": "obj"
}

You're trying to read the 1st argument passed to the program, which is wrong. 您正在尝试读取传递给程序的第一个参数,这是错误的。

When using pipes the stream is redirected to the programs stdin. 使用管道时,流将重定向到程序stdin。 You should read from sys.stdin, see " How do you read from stdin in python ". 您应该阅读sys.stdin,请参阅“ 如何从python中的stdin中阅读 ”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM