Description of setting a one-dimensional array in json

Asked 1 years ago, Updated 1 years ago, 53 views

I am currently studying Python and am writing a program using the API.
However, I would like to use a one-dimensional array for the values to be set in JSON, but it does not work.
How should I describe it?

It may be difficult to understand, but could you tell me...

This is ↓

json_data={
    'destination': {
        'XXX': XX,
    },
    'source': {
        'ipRanges': [
            "11111", // ★ I want to arrange it here
            "22222" // ★ I want this to be an array
          ]
    }
}

The image is ↓, which I want to do like this. (It will be an error...)

json_data={
    'destination': {
        'XXX': XX,
    },
    'source': {
        'ipRanges': [
            test["values"] // ★ I did not mention the array, but I would appreciate it if you could consider it as defined.
          ]
    }
}

python json api array

2022-09-30 19:27

1 Answers

Is this the image?

import json
r_array=[
    [1, 2, 3, 4, 5],
    [3, 5, 7, 8, 9],
]

json_data = {
    'destination': {
        'XXX': "XX",
    },
    'source': {
        'ipRanges': r_array
    }
}

print(json_data)

json_str=json.dumps(json_data,indent=2)

print(json_str)

Output:

{'destination':{'XXX':'XX'}, 'source':{'ipRanges':[[1,2,3,4,5],[3,5,7,8,9]]}}
{
  "destination": {
    "XXX": "XX"   
  },
  "source": {
    "ipRanges": [
      [
        1,
        2,
        3,
        4,
        5
      ],
      [
        3,
        5,
        7,
        8,
        9
      ]
    ]
  }
}

<Additional: With Numpy >

from array import array


import json
import numpy as np

ra_array=np.array(
    [
        [0, 1, 2],
        [3, 4, 5],
        [6, 7, 8]
    ]
)


json_data = {
    'destination': {
        'XXX': "XX",
    },
    'source': {
        'ipRanges':ra_array.tolist()
    }
}

print(json_data)

json_str=json.dumps(json_data,indent=2)

print(json_str)

If you want to handle the array, I think it would be more convenient to use Numpy, so I added it just in case.


2022-09-30 19:27

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.