Reputation: 126
So I tried to compress a JSON file and decompress it using this code (the two built function)
the compressing process works fine, but I can't figure out how to decompress it back to JSON, so I can append more items to it.
this is what I have tried:
path = r"mypath.json"
print(json_zip(path))
with open(path, "w") as f:
json.dump(json_zip(path), f, ensure_ascii=False, indent=4)
with open(path, "r") as f:
file_data = json.load(f)
print(json_unzip(file_data))
print output:
{'base64(zip(o))': 'eJwNyjEKgDAQBdGrLOn1AHYaUewEsftNiKuskawkInh7U80rxtgGWDOnDHTMSYBR9biY+iQvA4NEF31BN4sP5Voe9YGmuCuwObk+2tzjyOv9UUW2BGjrM2s0PzCOIWs='}
C:\Users\Beeri\Google Drive\Finance\BPicks\Stock Info\daily data copy - Copy\A.json
maybe I don't get the concept of decompression right, but I want the JSON to look like it was before. the JSON itself looks something like this:
[
{
"date": "2020-05-18 16:00:00",
"open": 83.79,
"low": 83.67,
"high": 83.79,
"close": 83.67,
"volume": 1855946
},
{
"date": "2020-05-18 15:59:00",
"open": 83.815,
"low": 83.77,
"high": 83.83,
"close": 83.79,
"volume": 1822469
},
{
"date": "2020-05-18 15:58:00",
"open": 83.9,
"low": 83.78,
"high": 83.9,
"close": 83.815,
"volume": 1803855
}
]
Upvotes: 1
Views: 1152
Reputation: 9047
according to your code:
>>> compressed_json = data['base64(zip(o))']
>>> decompressed_json = zlib.decompress(b64decode(compressed))
>>> decompressed_json
b'"C:\\\\Users\\\\Beeri\\\\Google Drive\\\\Finance\\\\BPicks\\\\Stock Info\\\\daily data copy - Copy\\\\A.json"'
>>> json.loads(decompressed_json)
'C:\\Users\\Beeri\\Google Drive\\Finance\\BPicks\\Stock Info\\daily data copy - Copy\\A.json'
As mentioned by Karl, you basically compressed the file path not the actual file: try this
import zlib, json
from base64 import b64encode, b64decode
path = r"filename.json"
def compress_json(data):
return {'base64(zip(o))': b64encode(zlib.compress(json.dumps(data).encode('utf-8'))).decode()}
def decompress_json(data):
compressed_json = data['base64(zip(o))']
return json.loads(zlib.decompress(b64decode(compressed_json)))
with open(path, "r") as f:
data = f.read()
compressed_json = compress_json(data)
print(compressed_json)
"""
{'base64(zip(o))': 'eJxTio7JUwCCaggFAjFKKYklqTFKVkCWkYGRga6Bqa6hhYKhmZW
BARDFKOkgq80vSM0DqbUw1jO3RJHJyS+HSpiZo0hkZKZnYNeSnJNfnIpdU1l+TmkuWM7QwtT
U0sQMIlmrQ7T7Ta1MLfG638LQFIcHzHF6wMIYpwfQ/IbsASMjEzNLcjxggdcDuMLf3AKX83EH
P3pgIDvfwBgYBVDnx+TFKgEASGiHCQ=='}
"""
decompressed_json = decompress_json(compressed_json)
print(decompressed_json)
"""
[
{
"date": "2020-05-18 16:00:00",
"open": 83.79,
"low": 83.67,
"high": 83.79,
"close": 83.67,
"volume": 1855946
},
{
"date": "2020-05-18 15:59:00",
"open": 83.815,
"low": 83.77,
"high": 83.83,
"close": 83.79,
"volume": 1822469
},
{
"date": "2020-05-18 15:58:00",
"open": 83.9,
"low": 83.78,
"high": 83.9,
"close": 83.815,
"volume": 1803855
}
]
"""
Upvotes: 2