Created
December 26, 2019 07:46
-
-
Save msguner/25dfb46bcd611858ce0ca5dc89d80a54 to your computer and use it in GitHub Desktop.
Python replace placeholders in json
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) |
will it work also for deep nested json?
@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
Thanks a lot! Very useful for me...