簡體   English   中英

如何獲取特定的 json 值 - python

[英]How to get specific json value - python

我正在將我的代碼從 java 遷移到 python,但我仍然在理解如何使用 python 獲取 json 中的特定路徑時遇到一些困難。

這是我的 Java 代碼,它返回一個accountsId列表。

public static List < String > v02_JSON_counterparties(String date) {
    baseURI = "https://cdwp/cdw";
    String counterparties =
        given()
        .auth().basic(getJiraUser(), getJiraPass())
        .param("limit", "1000000")
        .param("count", "false")
        .when()
        .get("/counterparties/" + date).body().asString();

    List < String > accountId = extract_accountId(counterparties);
    return accountId;
}

public static List < String > extract_accountId(String res) {
    List < String > ids = JsonPath.read(res, "$..identifier[?(@.accountIdType == 'ACCOUNTID')].accountId");
    return ids;
}

這是我獲取accountID的 json 結構。

{
            'organisationId': {
                '#value': 'MHI'
            },
            'accountName': 'LAZARD AM DEUT AC LF1632',
            'identifiers': {
                'accountId': 'LAZDLF1632',
                'customerId': 'LAZAMDEUSG',
                'blockAccountCode': 'LAZDEUBDBL',
                'bic': 'LAMDDEF1XXX',
                'identifier': [{
                    'accountId': 'MHI',
                    'accountIdType': 'REVNCNTR'
                }, {
                    'accountId': 'LAZDLF1632',
                    'accountIdType': 'ACCOUNTID'
                }, {
                    'accountId': 'LAZAMDEUSG',
                    'accountIdType': 'MHICUSTID'
                }, {
                    'accountId': 'LAZDEUBDBL',
                    'accountIdType': 'BLOCKACCOUNT'
                }, {
                    'accountId': 'LAMDDEF1XXX',
                    'accountIdType': 'ACCOUNTBIC'
                }, {
                    'accountId': 'LAZDLF1632',
                    'accountIdType': 'GLOBEOP'
                }]
            },
            'isBlocAccount': 'N',
            'accountStatus': 'COMPLETE',
            'products': {
                'productType': [{
                    'productLineName': 'CASH',
                    'productTypeId': 'PRODMHI1',
                    'productTypeName': 'Bond, Equity,Convertible Bond',
                    'cleared': 'N',
                    'bilateral': 'N',
                    'limitInstructions': {
                        'limitInstruction': [{
                            'limitAmount': '0',
                            'limitCurrency': 'GBP',
                            'limitType': 'PEAEXPLI',
                            'limitTypeName': 'Cash-Peak Exposure Limit'
                        }]
                    }
                }]
            },
            'etc': {
                'addressGeneral': 'LZFLUS33XXX',
                'addressAccount': 'LF1632',
                'tradingLevel': 'B'
            },
            'clientBroker': 'C',
            'costCentre': 'Credit Sales',
            'clientLevel': 'SUBAC',
            'accountCreationDate': '2016-10-19T00:00:00.000Z',
            'accountOpeningDate': '2016-10-19T00:00:00.000Z'
        }

這是我在 Python 中的代碼

import json, requests, urllib.parse, re
from pandas.io.parsers import read_csv
import pandas as pd
from termcolor import colored
import numpy as np
from glob import glob
import os

# Set Up
dateinplay = "2021-09-27"

#Get accountId
cdwCounterparties = (
    f"http://cdwu/cdw/counterparties/?limit=1000000?yyyy-mm-dd={dateinplay}"
)
r = json.loads(requests.get(cdwCounterparties).text)

account_ids = [i['accountId'] for i in data['identifiers']['identifier']if i['accountIdType']=="ACCOUNTID"]

當我嘗試獲取 accountId 時出現此錯誤:

Traceback (most recent call last):
  File "h:\DESKTOP\test_check\checkCounterpartie.py", line 54, in <module>
    account_ids = [i['accountId'] for i in data['identifiers']['identifier']if i['accountIdType']=="ACCOUNTID"]
TypeError: list indices must be integers or slices, not str
accs = {
  "identifiers": {
...
account_id_list = []
for acc in accs.get("identifiers", {}).get("identifier", []):
    account_id_list.append(acc.get("accountId", ""))

創建一個名為 account_id_list 的列表,它是

['MHI',  'DKEPBNPGIV',  'DKEPLLP SG',  'DAVKEMEQBL',  '401821',  'DKEPGB21XXX',  'DKEPBNPGIV',  'DKPARTNR']

假設您將字典(json 結構)存儲在變量x ,獲取所有accountIDs類似於:

account_ids = [i['accountId'] for i in x['identifiers']['identifier']]

如果我正確地回答了您的問題,您需要 accountistype 為“ACCOUNTID”的所有 ID。

這給你:

 account_ids = [i['accountId'] for i in data['identifiers']['identifier']if i['accountIdType']=="ACCOUNTID"]

我要感謝大家的回答。 它對我找到解決問題的方法有很大幫助。 下面是我解決它的方法。

listAccountId = []
cdwCounterparties = (
f"http://cdwu/cdw/counterparties/?limit=100000?yyyy-mm-dd={dateinplay}"
)

r = requests.get(cdwCounterparties).json()

jsonpath_expression = parse("$..accounts.account[*].identifiers.identifier[*]")

for match in jsonpath_expression.find(r):
    # print(f'match id: {match.value}')
    thisdict = match.value
    if thisdict["accountIdType"] == "ACCOUNTID":
        #   print(thisdict["accountId"])
        listAccountId.append(thisdict["accountId"])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM