I noticed that if you use the simplejson function in django all the strings are enclosed with single quotes, and the whole json object string is enclosed in double quotes. When I take this string and hand it in to JSON.parse, it gives me an error because they want to use single quotes to enclose the whole object and double quotes for the strings. I could switch them with javascript replace, but then I'd have to take into consideration cases like apostrophes, but I'm sure there is a better way. Is there a way to get django's simplejson to output the object string to the format of JSON.parse?
More info:
django view:
def view(request):
list = [{"a":"apple",},]
return HttpResponse(simplejson.dumps(str(list)), mimetype="application/json")
what the javascript string turn out to be
"[{'a': 'apple'}]"
update
remove the str() around list, simply simplejson.dumps(list). str() trans the list to a string, thus you got "[{'a': 'apple'}]" in client side.
Can you update the question to demo where simplejson encloses strings w/ single quotes?
django.utils.simplejson, normally, conforms w/ JSON specification and does not use single quotes to wrap things. If you mean
>>> from django.utils.simplejson import dumps
>>> dumps("Hello")
'"Hello"' # single quotes here
>>> repr(dumps("Hello"))
'\'"Hello"\'' # or here
They're notations of Python, you don't want to directly use them in JSON.parse (the first one is OK though).
Related
I should construct and pass following text in my JSON scheme. Here is how it should look:
r"""any-text-goes-here"""
Here is how I decided to construct it:
function make(text) {
return `r"""${text}"""`;
}
The function above takes any string and converts it to desired format. But, when I return it in my API as one of fields of JSON, it looks like following:
"r\"\"\"any-text-goes-here\"\"\""
I want to avoid backslashes. I understand that those slashes is needed by Javascript to properly work, but can I remove them, because client side awaits how I described above. Is it possible technically? How can I solve problem?
JSON strings are delimited by " characters.
" characters can be included in a JSON string only by using an escape sequence.
Escape sequences start with a \.
You can't avoid the backslashes.
See the grammar from the JSON website:
I have a Xamarin Forms app that is calling javascript and sending as a parameter a JSON string that contains a path. When it leaves c# the back slashes have been double-escaped like this:
"myreturnfunc('', '{\"statusCode\":\"200\",\"path\":\"\\\\temp\\\\Uploads\\\\100650\\\\IMG_20200107_094705_5.jpg\"}');"
but when it gets into myreturnfunc only single back slashes remain:
"{"statusCode":"200","path":"\temp\Uploads\100650\IMG_20200107_094705_5.jpg"}"
which fails on JSON.parse. What do I need to do to allow the escaped \'s to come through? I call this method from another javascript function as well, and when called from there it comes through in the correct format:
"{"path":"\\temp\\Uploads\\100650\\IMG_20200107_094705_5.jpg","statusCode":"200"}"
Json.parse typically encounters two escapes when the json.parse parameter contains the transition characters, the first being the escape of the string itself and the second being the escape of the actual js object.
for example,your string \"path\":\"\\\\temp\\\\Uploads\\\\100650\\\\IMG_20200107_094705_5.jpg\" above
First parser extracted strings think first \ escape the second \ and the third \ escape the fourth \, that is to say, the actual output string is "path":"\\temp\\Uploads\\100650\\IMG_20200107_094705_5.jpg" (could be verified by console.log)
Then there is another escape when it is formally converted to a js object,the finally result will be "path":"\temp\Uploads\100650\IMG_20200107_094705_5.jpg"
So if you want one \ in a js object, you need four \ in a json string
I need to read dot ner reesources string in java script as mention below.
var resources = #Html.ResourceStrings("Home_General_", Resources.ResourceManager);
The above line will render all the resources (from Dot net resource file) which start with resource key as "Home_General_"
Some of the values from the resources are like "Hi "XYZ" are you there" i.e The string contains quotes character.
If the string has quotes the above call fails.
The one way to avoid this problem is escape the special character as "Hi \"XYZ\" are you there"
Any other way where we can avoid this, As I don't want to pollute my resource string with lot of escape (\) characters.
You need to Javascript-escape any string when you render it as a Javascript string literal.
You must also remove the outer quotes from the string resource; that should be text, not a half-valid Javascript expression.
Use code like this to retrieve a single resource string:
var resourceXYZ = '#Html.Raw(HttpUtility.JavaScriptStringEncode(Resources.ResourceManager.GetString("Home_General_XYZ")))';
We do the following:
We get the resource string via Resources.ResourceManager.GetString().
We pass the result to HttpUtility.JavaScriptStringEncode to escape any special characters in JavaScript.
We pass the result to Html.Raw() to prevent Razor from applying HTML encoding on this string.
We then output the text enclosed in single quote quaracters into the page.
The function Html.ResourceStrings is not a standard function that is part of MVC. Someone at your place must have written it. If you show us this code, we could tell you how to rewrite it to return valid JavaScript literals.
You could wrap your #Html.ResourcesString(...) with HttpUtility.JavaScriptStringEncode which will handle all escape issues.
var resources = #HttpUtility.JavaScriptStringEncode(Html.ResourceStrings("Home_General_", Resources.ResourceManager));
I ran two pieces of javascript codes in a online JS running platform:Website Link
pets = '{'pet_names':[{"name":"jack"},{"name":"john"},{"name":"joe"}]}';
var arr = JSON.parse(pets);
alert(arr.pet_names[1].name);
Code with double quotes ("pet_names") would be OK but with single quotes('pet_names') would remind a error:"Unexpected identifier"
pets = '{"pet_names":[{"name":"jack"},{"name":"john"},{"name":"joe"}]}';
var arr = JSON.parse(pets);
alert(arr.pet_names[1].name);
So, why do it would happen?
In JSON only double quotes are valid.
You can find the standard on JSON.org
A value can be a string in double quotes, or a number, or true or
false or null, or an object or an array. These structures can be
nested.
In other words, no strings in single quotes.
The first one didn't work because you have a syntax error where you try to define your string literal
you probably wanted
pets = '{\'pet_names\':[{"name":"jack"},{"name":"john"},{"name":"joe"}]}';
notice the quotes are escaped.
Now if you used that string in the json parser you would still get an error(SyntaxError: Unexpected token ') because keys in JSON must be defined with double quotes, using single quotes is valid for defining JavaScript object literals which is separate from JSON.
I am using Dojo.fromJson to convert json string to javascript object, but throw exception. Because, there are control characters such as ',\n,\r in the json string.
How can I solve this problem in dojo? convert json string to javascript object, even if there are control characters.
I use Newtonsoft.JsonConvert.SerializeObject to convert C# oject to json data. Json Object: {"name":"'\"abc\n123\r"} then, I use Dojo.fromJson(' {"name":"'\"abc\n123\r"}') to convert json data to javascript object.
Thank you very much!
Problem, i believe is the double-quote which should be escaped by triple backslashes. You can use "native browser JSON decode" as searchterm for "dojo fromJson" synonym.
Without knowing my way around C# - I havent tested but i believe following should work:
string c_sharp_name = "'\"abc\n123\r";
// C#Object.name
c_sharp_name = c_sharp_name.
replace('"', '\\"'). // maybe add a slash on serverside
replace('\n', '\\\n').
replace('\r', '\\\r');
since
while this fails:
{"name":"'\"abc\n123\r"} // your single backslash
this would work:
{"name":"'\\\"abc\\\n123\\\r"} // working triple backslash escape