B
B
Bl4ckm45k2020-08-27 18:48:17
Python
Bl4ckm45k, 2020-08-27 18:48:17

Find out the number of JSON arrays and subarrays in Python?

There is an array like:

[
  {
    "number": "53223",
    "internalNumber": "321091",
    "positions": [
    {
        "id": "1613",
        "statusCode": "62571"
    },
      {
        "id": "1614",
        "statusCode": "62571"
    }
    ]
    },
     {
    "number": "53243182",
    "internalNumber": "321091352",
  "positions": [
  {
        "id": "1644",
        "statusCode": "62571"
    }
    ]
    }
  ]


The number of arrays and subarrays is unknown before the request to the server

From each subarray, you need to get the "statusCode" value and pass it as a parameter to the GET request
param = data[0]['positions'][0]["statusCode"]
url1 = SetOrderStURL + param

Change = requests.get(url1, verify=False)
Change.encoding = "utf-8"
print(Change)


How to process an unknown number of JSON arrays, get data of a specific key( "statusCode": "62571") and send a GET request for each "statusCode" in sequence?
Thank you so much for reading, I don't know what to do

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alexander, 2020-08-27
@Bl4ckm45k

for param in [y["statusCode"] for x in data for y in x["positions"]]:
    Change = requests.get(SetOrderStURL + param, verify=False)
    Change.encoding = "utf-8"
    print(Change)

or
for x in data:
   for y in x["positions"]:
       Change = requests.get(SetOrderStURL + y["statusCode"], verify=False)
       Change.encoding = "utf-8"
       print(Change)

G
Gennady S, 2020-08-27
@gscraft

Um, why not just iterate in a loop?

# data[0]['positions'][0]["statusCode"]
for item in data:
  positions = data.get('positions')
  if isinstanceof(positions, list): # например, проверьте, если значение может быть пустым
    for position in positions:
      status_code = position.get('statusCode') # стоит всегда называть_переменные_змейкой
      if status_code == 'abc': pass # делайте, что Вам нужно

S
SKEPTIC, 2020-08-27
@pro100chel

import json

data = json.loads('[{"number": "53223","internalNumber": "321091","positions": [{"id": "1613","statusCode": "62571"},{"id": "1614","statusCode": "62571"}]},{"number": "53243182","internalNumber": "321091352","positions": [{"id": "1644","statusCode": "62571"}]}]')

for i in data:
  if 'positions' in i:
    for w in i['positions']:
      id = w['id']
      statusCode = w['statusCode']
      print(f"ID: {id}, STATUS CODE: {statusCode}")

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question