Skip to content

Instantly share code, notes, and snippets.

@msguner
Created December 26, 2019 07:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save msguner/25dfb46bcd611858ce0ca5dc89d80a54 to your computer and use it in GitHub Desktop.
Save msguner/25dfb46bcd611858ce0ca5dc89d80a54 to your computer and use it in GitHub Desktop.
Python replace placeholders in json
import re
def replace_json_placeholders(json, values):
# find all placeholders
placeholders = re.findall('<[\w ]+>', json)
# clear_placeholders = list(map(lambda x: x.replace('<', '').replace('>', ''), placeholders))
assert len(placeholders) == len(values), "Please enter the values of all placeholders."
# replaces all placeholders with values
for k, v in values.items():
placeholder = "<%s>" % k
json = json.replace(placeholder, v)
return json
#Example
json = "{'firstName':'<first_name>','lastName':'<last_name>','country':'Turkey','city':'Istanbul'}"
values = {'first_name':'muhammet','last_name':'guner'}
print(replace_json_placeholders(json,values))
@henhuy
Copy link

henhuy commented Nov 27, 2020

Thanks a lot! Very useful for me...

@avico78
Copy link

avico78 commented Oct 6, 2021

will it work also for deep nested json?

@cholthi
Copy link

cholthi commented Jul 27, 2023

@avico78 Yes . This code is a lexical search and replace which looks at given string as a single blob of data. nested placeholders with the same keyword may not work well

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment