【问题标题】:How to get specific json value - python如何获取特定的 json 值 - python
【发布时间】:2021-12-14 10:32:24
【问题描述】:

我正在将我的代码从 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

【问题讨论】:

  • 先向我们展示你在 Python 中的尝试,看看你是否遇到了问题
  • 如果数据结构没有来自 JSON,则与您从数据结构中获取值的方式相同。如果您不了解如何在 Python 中操作列表和字典,则需要遵循通用教程。 Python 的内置 JSON 库没有“路径”习语;它只是创建一个代表整个事物的数据结构,然后您可以正常使用该数据结构。
  • 无论如何,“请帮助我将代码从一种语言转换为另一种语言”不是可操作的 Stack Overflow 问题。请阅读How to Askmeta.stackoverflow.com/questions/261592/…。您应该首先尝试自己解决问题 - 使用您所询问的语言。
  • 抱歉问题类型,我应该添加我在 python 中已经拥有的内容。我编辑了到目前为止的帖子广告,但与 json 响应列表交互时出错。我编辑并添加了迄今为止在 python 中的代码。

标签: python json list rest


【解决方案1】:
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']

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      如果我正确地回答了您的问题,您需要 accountistype 为“ACCOUNTID”的所有 ID。

      这给你:

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

      【讨论】:

      • 感谢您的帮助,但它返回此错误。 TypeError:列表索引必须是整数或切片,而不是 str。
      • cdwCounterparties = ( f"cdwu/cdw/counterparties/?limit=1000000?yyyy-mm-dd={dateinplay}" ) data = json.loads(requests.get(cdwCounterparties).text) account_ids = [i['accountId'] for i in data[ 'identifiers']['identifier']if i['accountIdType']=="ACCOUNTID"] print(account_ids)
      • 哦。那么您的 json 的嵌套或格式可能与您发布的不同。如果您发布从回复中获得的实际数据,我可以帮助您聊天
      • 我已经更新了帖子中的json响应。
      • 这很奇怪。当我粘贴您的 json 时,我的代码有效。你确定你将数据作为字典吗?尝试检查数据类型&gt;&gt;&gt; type(data) &lt;class 'dict'&gt; 它应该返回这个。如果您的数据对象不是字典,您可以尝试在请求中使用 .json 属性而不是 .text
      【解决方案4】:

      感谢大家的回答。它对我找到解决问题的方法有很大帮助。 以下是我的解决方法。

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

      【讨论】:

        猜你喜欢
        • 2021-04-21
        • 2021-12-19
        • 2018-11-04
        • 2019-04-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-19
        相关资源
        最近更新 更多