arcpy.SetParameter() - Problem passing escaped string as geoprocessing service output

2128
16
12-19-2016 12:14 PM
MaximeDemers
Occasional Contributor III

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?

0 Kudos
16 Replies
JamesCrandall
MVP Frequent Contributor

Not sure if this is correct for the .dumps() but try setting strict param:

my_json = json.dumps(my_dict, strict=False)

 

0 Kudos
MaximeDemers
Occasional Contributor III

@James Crandall : There is no such parameter in json.dumps(), at least in python 2.7

0 Kudos
JamesCrandall
MVP Frequent Contributor

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)‍‍‍‍
0 Kudos
JamesCrandall
MVP Frequent Contributor

FYI: this still produces the OP's result.

0 Kudos
KevinHibma
Esri Regular Contributor

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... 

0 Kudos
MaximeDemers
Occasional Contributor III

Thank you, but the aim is to keep the the newlines. Removing it is not wanted.

0 Kudos
DanPatterson_Retired
MVP Emeritus
>>> 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
‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍
0 Kudos