I am working on a code that extracts data from a JSON file here is the JSON file: Google CDN
and here is a sample of JSON code:
{
"syncToken": "1677578581095",
"creationTime": "2023-02-28T02:03:01.095938",
"prefixes": [{
"ipv4Prefix": "34.80.0.0/15",
"service": "Google Cloud",
"scope": "asia-east1"
}, {
"ipv4Prefix": "34.137.0.0/16",
"service": "Google Cloud",
"scope": "asia-east1"
}, {
"ipv4Prefix": "35.185.128.0/19",
"service": "Google Cloud",
"scope": "asia-east1"
}, {
"ipv6Prefix": "2600:1900:40a0::/44",
"service": "Google Cloud",
"scope": "asia-south1"
},
I know where the problem is but can not fix the issue with solutions on this website and getting another error every time.
This is my code
import json
f = open('cloud.json')
data = json.load(f)
array = []
for i in data['prefixes']:
array = [i['prefix'] for i in data['ipv4Prefix']]
f_path = (r"ip.txt")
with open (f_path ,'w') as d:
for lang in array:
d.write("{}\n".format(lang))
f.close()
Basically I want to extract only ipv4 address but there are some ipv6 address randomly in block that causes this error so I get key error like this: KeyError: 'ipv4Prefix'
I know why I am getting this error so I tried deleting that whole entry with ipv6Prefix so I added this part to my code:
if data[i]["prefixes"] == "ipv6Prefix":
data.pop(i)
for this one I get TypeError: unhashable type: 'dict' which is new to me, I also tried this as someone pointed out in another question but it didn't work.
del data[ipv6Prefix]
Now my final code is like this and getting this error: TypeError: list indices must be integers or slices, not str which is understandable.
import json
f = open('cloud.json')
data = json.load(f)
array = []
for i in data['prefixes']:
if [i]["prefixes"] == ['ipv6Prefix']:
data.pop(i)
array = [i['prefix'] for i in data['ipv4Prefix']]
f_path = (r"ip.txt")
with open (f_path ,'w') as d:
for lang in array:
d.write("{}\n".format(lang))
f.close()
So how can I delete entries with 'ipv6Prefix' or better to say, ignore them in my for loop?
I found this question but answer does not fit my code at all.
what's the problem with my code?
I tried several methods like del
and dict.pop()
but still I get error.