Home > Software engineering >  How to remove JSON data array (and keep its content) in Python
How to remove JSON data array (and keep its content) in Python

Time:05-10

I am programming a tool with the Roblox API. My code to request data from Roblox's API is below, it stores it and uses it later (not related to this issue)

import requests
from requests.exceptions import HTTPError
import json

try:
    response = requests.get('https://groups.roblox.com/v2/groups?groupIds=10491230') # example random group
    response.raise_for_status()
    # access JSOn content
    json1 = response.json()
    print(json1)

except HTTPError as http_err:
    print(f'HTTP error occurred: {http_err}')
except Exception as err:
    print(f'Other error occurred: {err}')

The output is below (value of json1)

{
  "data": [
    {
      "id": 0,
      "name": "string",
      "description": "string",
      "owner": {
        "id": 0,
        "type": "User",
        "name": "string"
      },
      "memberCount": 0,
      "created": "2022-05-09T16:16:38.105Z"
    }
  ]
}

Since I need to parse and interact with the data in the data[] array, I need to remove it, so the output would be simular to the output below.

{
  "id": 0,
  "name": "string",
  "description": "string",
  "owner": {
    "id": 0,
    "type": "User",
    "name": "string"
  },
  "memberCount": 0,
  "created": "2022-05-09T16:16:38.105Z"
}

How would I remove the data[] part, but keep the data inside? I tried replace() and JSON parsing, but have no idea how to start.

Language: Python

Thanks!

API documentation is available at https://groups.roblox.com/docs#!/Groups/get_v2_groups

CodePudding user response:

This should work

json1 = response.json()["data"]

CodePudding user response:

You can store content inside data array in another variable

data = json1["data"][0]

or if you want the whole array

data = json1["data"]
  • Related