Skip to content

Instantly share code, notes, and snippets.

@devinou971
Created April 26, 2026 20:28
Show Gist options
  • Select an option

  • Save devinou971/a83e4e1f352bd0f76b40cb636618e343 to your computer and use it in GitHub Desktop.

Select an option

Save devinou971/a83e4e1f352bd0f76b40cb636618e343 to your computer and use it in GitHub Desktop.
Replacing measures in PowerBI Reports exported with pbi-tool
import glob
import json
import os
import shutil
SOURCE_FOLDER = "test_ssas"
OUTPUT_FOLDER = "test_ssas_copy"
MEASURE_TO_REPLACE = "_tests"
SOURCE_TABLE = "Table"
REPLACE_MEASURE_WITH = "_tests_"
REPLACE_TABLE_WITH = "Table"
files = glob.glob("**/*.json", root_dir=SOURCE_FOLDER, recursive=True)
if OUTPUT_FOLDER != SOURCE_FOLDER and not os.path.exists(OUTPUT_FOLDER):
os.mkdir(OUTPUT_FOLDER)
shutil.copytree(SOURCE_FOLDER, OUTPUT_FOLDER, dirs_exist_ok=True)
def get_nodes_by_name(src: dict | list, name: str):
results = []
if name in src:
results.append(src)
if type(src) == list:
for subnode in src :
if type(subnode) == dict or type(subnode) == list:
results += get_nodes_by_name(subnode, name)
elif type(src) == dict :
for key in src.keys():
if type(src[key]) == dict or type(src[key]) == list:
results += get_nodes_by_name(src[key], name)
return results
def replace(json_obj: dict, property_to_replace, value_to_replace, replace_with):
nodes = get_nodes_by_name(json_obj, property_to_replace)
for node in nodes :
if node[property_to_replace] == value_to_replace:
node[property_to_replace] = replace_with
for file_path in files :
print(file_path)
with open(SOURCE_FOLDER+os.path.sep+file_path, "r", encoding="utf-8") as f :
json_file = json.loads(f.read())
replace(json_file, "Property", MEASURE_TO_REPLACE, REPLACE_MEASURE_WITH)
replace(json_file, "NativeReferenceName", MEASURE_TO_REPLACE, REPLACE_MEASURE_WITH)
replace(json_file, "Restatement", MEASURE_TO_REPLACE, REPLACE_MEASURE_WITH)
replace(json_file, "queryRef", SOURCE_TABLE+"."+MEASURE_TO_REPLACE, REPLACE_TABLE_WITH + "." + REPLACE_MEASURE_WITH)
replace(json_file, "queryName", SOURCE_TABLE+"."+MEASURE_TO_REPLACE, REPLACE_TABLE_WITH + "." + REPLACE_MEASURE_WITH)
replace(json_file, "Name", SOURCE_TABLE+"."+MEASURE_TO_REPLACE, REPLACE_TABLE_WITH + "." + REPLACE_MEASURE_WITH)
folder_path = os.path.sep.join((OUTPUT_FOLDER + os.path.sep + file_path).split(os.path.sep)[:-1])
os.makedirs(folder_path, exist_ok=True)
with open(OUTPUT_FOLDER + os.path.sep + file_path, "w", encoding="utf-8") as f :
json.dump(json_file, f, indent=4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment