forked from GoogleChrome/lighthouse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjson_roundtrip_via_proto.py
43 lines (33 loc) · 1.24 KB
/
json_roundtrip_via_proto.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import os
import sys
import json
import subprocess
import lighthouse_result_pb2 as lhr_pb2
from google.protobuf.json_format import Parse, MessageToJson
path = os.path.realpath(__file__)
path_dir = os.path.dirname(path)
path_sample_preprocessed = path_dir + '/sample_v2_processed.json'
path_sample = path_dir + '/../../lighthouse-core/test/results/sample_v2.json'
path_round_trip = path_dir + '/../sample_v2_round_trip.json'
def clean():
try:
os.remove(path_sample_preprocessed)
except OSError:
pass
# clean workspace
clean()
# preprocess the sample json
cmd = ["node", "./../../lighthouse-core/lib/proto-preprocessor.js", "--in=./../../lighthouse-core/test/results/sample_v2.json", "--out=./sample_v2_processed.json"]
process = subprocess.call(cmd)
# open json
with open(path_sample_preprocessed, 'r') as f:
data = json.load(f)
# make empty proto lhr
proto_lhr = lhr_pb2.LighthouseResult()
# fill proto lhr with data from JSON
Parse(json.dumps(data), proto_lhr)
# convert proto back into json
round_trip_lhr = json.loads(MessageToJson(proto_lhr, including_default_value_fields=False))
# write the json to disk
with open(path_round_trip, 'w') as f:
json.dump(round_trip_lhr, f, indent=4, sort_keys=True, separators=(',', ': '))