0

I have this array inside a JSON object document. The IpAddresses array has around 2.000 elements

{
   "IpAddresses": [
    "18.213.123.130/32",
    "3.217.79.163/32",
    "3.217.93.44/32",
    .
    .
  ] 
}

I want to convert it to this way:

[
    {
        "ipAddress" : "18.213.123.130/32"
    },
    {
        "ipAddress" : "3.217.79.163/32"
    },
    {
        "ipAddress" : "3.217.93.44/32"
    },
    .
    .
]

I am trying to do it by using json package in python

myArray = ["18.213.123.130/32",
           "3.217.79.163/32",
           "3.217.93.44/32"
          ]

ip_addresses = {item: "ipAddress" for item in myArray}
json_str_ip_adresses = json.dumps(ip_addresses)
print(repr(json_str_ip_adresses))

But the output I got is the following:

> python array-json.py
'{"18.213.123.130/32": "ipAddress", "3.217.79.163/32": "ipAddress", "3.217.93.44/32": "ipAddress"}

I am getting all my elements inside a JSON document, but what I want is to get every element inside myArray as a JSON document with an "ipAddress" key, something like this:

> python array-json.py
'{"ipAddress" : "18.213.123.130/32"}, {"ipAddress":"3.217.79.163/32", {"ipAddress":"3.217.93.44/32"}'

What is the best way to do it?

2 Answers 2

2

You can use list comprehension as:

ip_addresses = [{"ipAddress": item} for item in myArray]

Also, you don't need json.dumps() and repr() to convert back and forth.

Sign up to request clarification or add additional context in comments.

Comments

1
data = { "IpAddresses": [ "18.213.123.130/32", "3.217.79.163/32", "3.217.93.44/32" ] }
[{"ipAddress": i} for i in data["IpAddresses"]]

Result:

[{'ipAddress': '18.213.123.130/32'},
 {'ipAddress': '3.217.79.163/32'},
 {'ipAddress': '3.217.93.44/32'}]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.