1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Python から JavaScript ソース(zlib 圧縮データも含める)を生成

Last updated at Posted at 2018-03-04

こんにちは。
Python から JavaScript ソースを生成し、その中には JSON データを直書きしてみました。また書き込みデータは zlib 圧縮しました。このソースが実行されると元通りのデータ内容が得られました(伸長には pako.min.js を使用、下記例では console.log() へ表示)。

temp.html
$ ./print_html.py > temp.html
$ cat temp.html
<script src="pako.min.js"></script>
<script>
var jsonz = "789cab56caad54b252502a2e2d482d52d251502a0033ac14a24d4ccd74144ccdcc63818289e5a9c5f9b9a920850589d9f94ab500bf3b1015";
console.log(parse(jsonz));

function parse(hexstr) {
  return JSON.parse(pako.inflate(unhexlify(hexstr), {to: 'string'}));
}
function unhexlify(hexstr) {
  var result = '';
  for (var i=0, l=hexstr.length; i<l; i+=2) {
  result += String.fromCharCode(parseInt(hexstr.substr(i, 2), 16));
  }
  return result;
}
</script>
print_html.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import json, zlib

jsondata = {'my': 'super', 'puper': [456, 567], 'awesome': 'pako'}

jsonz = zlib.compress(json.dumps(jsondata).encode()).hex()
js = f'''
var jsonz = "{jsonz}";
console.log(parse(jsonz));
'''
js += '''
function parse(hexstr) {
  return JSON.parse(pako.inflate(unhexlify(hexstr), {to: 'string'}));
}
function unhexlify(hexstr) {
  var result = '';
  for (var i=0, l=hexstr.length; i<l; i+=2) {
  result += String.fromCharCode(parseInt(hexstr.substr(i, 2), 16));
  }
  return result;
}
'''

html = f'''
<script src="pako.min.js"></script>
<script>{js}</script>'''

print(html)
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?