I have a geoservice that get some text stored from a table in order to return a json string to a javascript client. However, the arcpy.SetParameter()
seems to have problem to returns the escaped new lines character (\\n
)
my_dict = {"key1" : "test is a string with\nsome escaped characters\nsuch newlines"}
my_json = json.dumps(my_dict)
print(my_json)
>>> '{"key1": "test is a string with\\nsome escaped characters\\nsuch newlines"}'
arcpy.SetParameter(0, my_json)
in the javascript console the response is the following which is not a valid json:
{"key1" : "test is a string with
some escaped characters
such newlines"}
Is there a solution?
Not sure if this is correct for the .dumps() but try setting strict param:
my_json = json.dumps(my_dict, strict=False)
@James Crandall : There is no such parameter in json.dumps(), at least in python 2.7
Turn the dictionary into a string, then try to load that with the strict param:
my_dict = '{"key1" : "test is a string with\\nsome escaped characters\\nsuch newlines"}'
my_jsonloads = json.loads(my_dict, strict=False)
my_json = json.dumps(my_jsonloads)
print(my_json)
FYI: this still produces the OP's result.
I'm late to this, but if the goal is to simply remove the escaped chars, try:
re.sub(r"\s", " ", my_dict['key1'])
>> 'test is a string with some escaped characters such newlines'
From the comment: string - Python - Why does str.strip() automatically removes all the escape characters? - Stack Over...
Thank you, but the aim is to keep the the newlines. Removing it is not wanted.
>>> import json
>>> dir(json)
['JSONDecodeError', 'JSONDecoder', 'JSONEncoder', '__all__', '__author__',
'__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__',
'__package__', '__path__', '__spec__', '__version__', '_default_decoder',
'_default_encoder', 'decoder', 'dump', 'dumps', 'encoder', 'load', 'loads',
'scanner']
>>> # above in python 3.5
>>>
>>> # now over to old-school
>>> import json
>>> dir(json)
['JSONDecoder', 'JSONEncoder', '__all__', '__author__', '__builtins__',
'__doc__', '__file__', '__name__', '__package__', '__path__', '__version__',
'_default_decoder', '_default_encoder', 'decoder', 'dump', 'dumps', 'encoder',
'load', 'loads', 'scanner']
>>> # above in python 2.7