mamolx
mamolx

Reputation: 23

How to slice a json file?

I'm trying to slice a json file to make it work properly: JSON file

Problem is the json file starts with var Nations =.

var Nations = {"Nations":[{"Name":"Neutral","CanBeUsedAsBotFiller":false,....

So I'm trying to get rid of it by slicing it off and saving it again:

import urllib.request

urlData = 'http://storage.googleapis.com/nacleanopenworldprodshards/Nations_cleanopenworldprodeu1.json'
webURL = urllib.request.urlopen(urlData)
data = webURL.read()
sliced_data = data[14:][:-1]

f = open(r'file.json', 'w')
f.write(str(sliced_data))
f.close()

But the saved file shows a b'

b'{"Nations":[{".....

How do I correctly get rid of it and have a json file that I can use in Python?

Upvotes: 0

Views: 2365

Answers (2)

user650881
user650881

Reputation: 2505

If you decode as utf-8 it will convert the byte string to string.

f.write(sliced_data.decode('utf-8'))

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599956

The data is downloaded from the internet, therefore it's bytes. So you need to open the file as binary.

Note also you can make things shorter by using a context handler; and you can do both parts of the slice in one go:

sliced_data = data[14:-1]

with f as open(r'file.json', 'wb')
    f.write(str(sliced_data))

Upvotes: 2

Related Questions