granite-guardian-3.1-8b / convert_to_string.py
Martín Santillán Cooper
Continue adaptation
6047b61
raw
history blame contribute delete
897 Bytes
import json
def dict_to_json_with_newlines(data):
"""
Converts a dictionary into a JSON string with explicit newlines (\n) added.
Args:
data (dict): The dictionary to convert.
Returns:
str: A JSON string with newlines represented as \n.
"""
# Convert the dictionary to a pretty-printed JSON string
pretty_json = json.dumps(data, indent=2)
# Replace actual newlines with escaped newlines (\n)
json_with_newlines = pretty_json.replace("\n", "\\n")
# Escape double quotes for embedding inside other JSON
json_with_newlines = json_with_newlines.replace('"', '\\"')
return json_with_newlines
# Example dictionary
example_dict = [{"name": "comment_list", "arguments": {"video_id": 456789123, "count": 15}}]
# Convert the dictionary
result = dict_to_json_with_newlines(example_dict)
print("Resulting JSON string:")
print(result)