【问题标题】:How to parse json in bash or pass curl output to python script如何在 bash 中解析 json 或将 curl 输出传递给 python 脚本
【发布时间】:2012-03-07 11:21:12
【问题描述】:

我正在寻找某种方法来以 json 格式打印 curl 的输出。 我为此目的编写了简短的python脚本,但它不适用于管道 我也不想使用子进程并从它们运行 curl:

所以蟒蛇:

#!/usr/bin/python

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

而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}]}]}}}

【问题讨论】:

    标签: python json bash pprint


    【解决方案1】:

    在 shell 中使用json.tool 进行验证和漂亮打印:

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

    【讨论】:

    • 谢谢你们。我试图找到这两种解决方案。他们都很好。
    【解决方案2】:

    您正在尝试读取传递给程序的第一个参数,这是错误的。

    当使用管道时,流被重定向到程序标准输入。您应该从 sys.stdin 中读取,请参阅“How do you read from stdin in python”。

    【讨论】:

      猜你喜欢
      • 2020-05-24
      • 2021-12-13
      • 2021-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-29
      • 2019-03-11
      相关资源
      最近更新 更多