如何从JSON提取数据

时间:2019-09-04 21:18:50

标签: python json

我想从JSON格式提取代码。

import json
json_data = '''
    {
        "Body": {
            "stkCallback": {
                "MerchantRequestID": "22531-976234-1",
                "CheckoutRequestID": "ws_CO_DMZ_250600506_23022019144745852",
                "ResultCode": 0,
                "ResultDesc": "The service request is processed successfully.",
                "CallbackMetadata": {
                    "Item": [
                        {
                            "Name": "Amount",
                            "Value": 1.0
                        },
                        {
                            "Name": "MpesaReceiptNumber",
                            "Value": "NBN52K8A1J"
                        },
                        {
                            "Name": "Balance"
                        },
                        {
                            "Name": "TransactionDate",
                            "Value": 20190223144807
                        },
                        {
                            "Name": "PhoneNumber",
                            "Value": 254725696042
                        }
                    ]
                }
            }
        }
    }
'''

json_da = data['Body']
list_data = data['Body']['MpesaReceiptNumber']
print (json_da)
print (list_data)

我要打印此:NBN52K8A1J

7 个答案:

答案 0 :(得分:0)

问题在于您需要首先搜索的dict列表:

>>> for obj in data['Body']['stkCallback']['CallbackMetadata']['Item']:
...   print(obj)
...
{'Name': 'Amount', 'Value': 1.0}
{'Name': 'MpesaReceiptNumber', 'Value': 'NBN52K8A1J'}
{'Name': 'Balance'}
{'Name': 'TransactionDate', 'Value': 20190223144807}
{'Name': 'PhoneNumber', 'Value': 254725696042}

一种可能性是

>>> [x['Value'] for x in data['Body']['stkCallback']['CallbackMetadata']['Item'] if x['Name'] == 'MpesaReceiptNumber'][0]
'NBN52K8A1J'

答案 1 :(得分:0)

只需使用库json。然后,您可以打印其内部元素

导入json

using System;
using System.Management.Automation;

namespace ConsoleApp1 {
    class Program {
        static void Main(string[] args) {
            string str;
            using (var ps = PowerShell.Create()) {
                str = "";
                var results = ps.AddScript("Get-Command").Invoke();
                foreach (var result in results) {
                    str += result.ToString() + ", ";
                }
            }
            Console.WriteLine(str);
        }
    }
}

答案 2 :(得分:0)

如果您解析json,您会注意到数据的路径不只是['Body'] ['MpesaReceiptNumber']。实际上,您需要在['Item']内搜索字典。

Parsed data tree

一个建议是运行以下代码以查找您要查找的数据:

import json
json_data = '{"Body":{"stkCallback":{"MerchantRequestID":"22531-976234-1","CheckoutRequestID":"ws_CO_DMZ_250600506_23022019144745852","ResultCode":0,"ResultDesc":"The service request is processed successfully.","CallbackMetadata":{"Item":[{"Name":"Amount","Value":1.00},{"Name":"MpesaReceiptNumber","Value":"NBN52K8A1J"},{"Name":"Balance"},{"Name":"TransactionDate","Value":20190223144807},{"Name":"PhoneNumber","Value":254725696042}]}}}}'
data = (json.loads(json_data))

list_data = data['Body']['stkCallback']['CallbackMetadata']['Item']

# Returns:
# [{'Name': 'Amount', 'Value': 1.0}, {'Name': 'MpesaReceiptNumber', 'Value':'NBN52K8A1J'}, {'Name': 'Balance'}, {'Name': 'TransactionDate', 'Value': 20190223144807}, {'Name': 'PhoneNumber', 'Value': 254725696042}]

# Now find Name: 'MpesaReceiptNumber' inside the dict list
find_it = next(item for item in list_data if item["Name"] == "MpesaReceiptNumber")
find_it = find_it['Value']

print (find_it)

结果

NBN52K8A1J

答案 3 :(得分:0)

您几乎就在那儿,只需要从字典中获取键值对本身,然后检查它是否是您想要的名称即可:

data = json.loads(json_data)
list_data = data['Body']["stkCallback"]['CallbackMetadata']['Item']
var: str

for x in list_data:
    if x['Name'] == 'MpesaReceiptNumber':
       var = x['Value']
       break

print(var)

将来,您可以通过将if校验替换为其他名称来轻松使用它,以便根据变量获取值。

答案 4 :(得分:0)

当您学习如何全部导航时,我发现使用pprint获取数据结构的形状很有帮助。

import json
import pprint

json_data = '{"Body":{"stkCallback":{"MerchantRequestID":"22531-976234-1","CheckoutRequestID":"ws_CO_DMZ_250600506_23022019144745852","ResultCode":0,"ResultDesc":"The service request is processed successfully.","CallbackMetadata":{"Item":[{"Name":"Amount","Value":1.00},{"Name":"MpesaReceiptNumber","Value":"NBN52K8A1J"},{"Name":"Balance"},{"Name":"TransactionDate","Value":20190223144807},{"Name":"PhoneNumber","Value":254725696042}]}}}}'
data = json.loads(json_data)

pprint.pprint(data)

结果:

{'Body': {'stkCallback': {'CallbackMetadata': {'Item': [{'Name': 'Amount', 'Value': 1.0},
                                                        {'Name': 'MpesaReceiptNumber', 'Value': 'NBN52K8A1J'},
                                                        {'Name': 'Balance'},
                                                        {'Name': 'TransactionDate', 'Value': 20190223144807},
                                                        {'Name': 'PhoneNumber', 'Value': 254725696042}]},
                          'CheckoutRequestID': 'ws_CO_DMZ_250600506_23022019144745852',
                          'MerchantRequestID': '22531-976234-1',
                          'ResultCode': 0,
                          'ResultDesc': 'The service request is processed successfully.'}}}

因此,您应该能够看到data["Body"]["stkCallback"]["CallbackMetadata"]["Item"]达到了数据所需的深度。

 >>> pprint.pprint(data["Body"]["stkCallback"]["CallbackMetadata"]["Item"])

 [{'Name': 'Amount', 'Value': 1.0},
 {'Name': 'MpesaReceiptNumber', 'Value': 'NBN52K8A1J'},
 {'Name': 'Balance'},
 {'Name': 'TransactionDate', 'Value': 20190223144807},
 {'Name': 'PhoneNumber', 'Value': 254725696042}]

因此,接下来您需要遍历该列表并为MpesaReceiptNumber键找到一个匹配项(如果存在)。

receipt_no = None
for item in data["Body"]["stkCallback"]["CallbackMetadata"]["Item"]:
    if item.get('Name') == 'MpesaReceiptNumber':
        receipt_no = item.get('Value')

print(f"The receipt # is: {receipt_no}")

答案 5 :(得分:0)

使用jq

首先,它可以“漂亮地打印”任何JSON数据。

json_data的值放入文件test.json中,然后使用以下命令显示JSON数据的格式化输出:

$ jq <test.json
{
  "Body": {
    "stkCallback": {
      "MerchantRequestID": "22531-976234-1",
      "CheckoutRequestID": "ws_CO_DMZ_250600506_23022019144745852",
      "ResultCode": 0,
      "ResultDesc": "The service request is processed successfully.",
      "CallbackMetadata": {
        "Item": [
          {
            "Name": "Amount",
            "Value": 1
          },
          {
            "Name": "MpesaReceiptNumber",
            "Value": "NBN52K8A1J"
          },
          {
            "Name": "Balance"
          },
          {
            "Name": "TransactionDate",
            "Value": 20190223144807
          },
          {
            "Name": "PhoneNumber",
            "Value": 254725696042
          }
        ]
      }
    }
  }
}

接下来,要提取值,需要在jq命令行上给出选择器路径:

jq '.Body.stkCallback.CallbackMetadata.Item|.[]|select(.Name == "MpesaReceiptNumber")|.Value' test.json
"NBN52K8A1J"

现在,为了使该序列更易于理解,让我们逐个细分它。

仅提取并返回.Body

$ jq '.Body' <test.json
{
  "stkCallback": {
    "MerchantRequestID": "22531-976234-1",
    "CheckoutRequestID": "ws_CO_DMZ_250600506_23022019144745852",
    "ResultCode": 0,
    "ResultDesc": "The service request is processed successfully.",
    "CallbackMetadata": {
      "Item": [
        {
          "Name": "Amount",
          "Value": 1
        },
        {
          "Name": "MpesaReceiptNumber",
          "Value": "NBN52K8A1J"
        },
        {
          "Name": "Balance"
        },
        {
          "Name": "TransactionDate",
          "Value": 20190223144807
        },
        {
          "Name": "PhoneNumber",
          "Value": 254725696042
        }
      ]
    }
  }
}

现在让我们获取stkCallback组件:

$ jq '.Body.stkCallback' <test.json
{
  "MerchantRequestID": "22531-976234-1",
  "CheckoutRequestID": "ws_CO_DMZ_250600506_23022019144745852",
  "ResultCode": 0,
  "ResultDesc": "The service request is processed successfully.",
  "CallbackMetadata": {
    "Item": [
      {
        "Name": "Amount",
        "Value": 1
      },
      {
        "Name": "MpesaReceiptNumber",
        "Value": "NBN52K8A1J"
      },
      {
        "Name": "Balance"
      },
      {
        "Name": "TransactionDate",
        "Value": 20190223144807
      },
      {
        "Name": "PhoneNumber",
        "Value": 254725696042
      }
    ]
  }
}

好,现在是callbackMetadata

$ jq '.Body.stkCallback.CallbackMetadata' <test.json
{
  "Item": [
    {
      "Name": "Amount",
      "Value": 1
    },
    {
      "Name": "MpesaReceiptNumber",
      "Value": "NBN52K8A1J"
    },
    {
      "Name": "Balance"
    },
    {
      "Name": "TransactionDate",
      "Value": 20190223144807
    },
    {
      "Name": "PhoneNumber",
      "Value": 254725696042
    }
  ]
}

接下来,Item部分:

$ jq '.Body.stkCallback.CallbackMetadata.Item' <test.json
[
  {
    "Name": "Amount",
    "Value": 1
  },
  {
    "Name": "MpesaReceiptNumber",
    "Value": "NBN52K8A1J"
  },
  {
    "Name": "Balance"
  },
  {
    "Name": "TransactionDate",
    "Value": 20190223144807
  },
  {
    "Name": "PhoneNumber",
    "Value": 254725696042
  }
]

注意到结果是列表项的 array 吗?让我们过滤数组的数据 out

$ jq '.Body.stkCallback.CallbackMetadata.Item|.[]' <test.json
{
  "Name": "Amount",
  "Value": 1
}
{
  "Name": "MpesaReceiptNumber",
  "Value": "NBN52K8A1J"
}
{
  "Name": "Balance"
}
{
  "Name": "TransactionDate",
  "Value": 20190223144807
}
{
  "Name": "PhoneNumber",
  "Value": 254725696042
}

现在结果只是元组列表,每个元组都有一个“名称”和“值”。因此,我们只选择我们(您)想要的一个:

$ jq '.Body.stkCallback.CallbackMetadata.Item|.[]|select(.Name == "MpesaReceiptNumber")' <test.json
{
  "Name": "MpesaReceiptNumber",
  "Value": "NBN52K8A1J"
}

很酷。我们有想要的元组。让我们现在只提取值:

$ jq '.Body.stkCallback.CallbackMetadata.Item|.[]|select(.Name == "MpesaReceiptNumber")|.Value' <test.json
"NBN52K8A1J"

然后,你去那里。

答案 6 :(得分:0)

获取与特定$(function() { $("#btnAddNew").button({ icons: { primary: "ui-icon-plus" }, label: "New" }); });项目名称关联的值的最简单方法:

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/cupertino/jquery-ui.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<button id="btnAddNew" type="button" title="New User Access" role="button" aria-disabled="false"></button>