简体   繁体   中英

How to get specific json value - python

I am migrating my code from java to python, but I am still having some difficulties understanding how to fetch a specific path in json using python.

This is my Java code, which returns a list of 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;
}

And this is the json structure where I am getting the accountID .

{
            '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'
        }

This is my code in 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"]

I am getting this error when I try to fetch the 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", ""))

creates a list called account_id_list which is

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

假设您将字典(json 结构)存储在变量x ,获取所有accountIDs类似于:

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

If I'm inerpeting your question correctly you want all ids where accountistype is "ACCOUNTID".

this give you that:

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

I'd like to thank you all for your answers. It helped me a lot to find a resolution to my problem. Below is how I solved it.

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"])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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