converting json string into json on client side? - c#

In my javascript code I am getting json string from cs file
var tmpString="<%=resultset2%>";
In cs I am concatenating strings to build json string. Here is an issue the json string is returned as a string and it has " with it.
"[{id:'1',name:'Aik'},{id:'2',name:'Aik or Aik'}]"
Because of " in beginning and end javascript code treat it as a string. Kindly guide me how I should sort out this issue.
thanks

Fix the JSON, it has errors (property names must be strings (and thus quoted), and only " are acceptable for quoting strings in JSON). JSON is a subset of JavaScript, you can't use all of JS' syntax in JSON. As a rule of thumb, if you are concatenating strings to produce a data format, then you are doing it wrong. http://json.org/ lists a number of C# libraries that you can use to build JSON.
Use json2.js

Change this:
var tmpString="<%=resultset2%>";
to:
var tmpString=<%=resultset2%>;
This isn't JSON, you're just writing javascript from a server page. The problem is you are creating invalid javascript syntax, you just need to remove the quotes.
The quotes aren't from resultset2 they are from your markup.

Related

C# Parse HTML Post Data

I have MemoryStream data (HTML POST Data) which i need to parse it.
Converting it to string give result like below
key1=value+1&key2=val++2
Now the problem is that all this + are space in html. Am not sure why space is converting to +
This is how i am converting MemoryStream to string
Encoding.UTF8.GetString(request.PostData.ToArray())
If you are using Content-Type of application/x-www-form-urlencoded, your data needs to be url encoded.
Use System.Web.HttpUtility.UrlEncode():
using System.Web;
var data = HttpUtility.UrlEncode(request.PostData);
See more in MSDN.
You can also use JSON format for POST.
I suppose that the data you are retrieving are encoded with URL rules.
You can discover why data are encoded to this format reading this simple article from W3c school.
To encode/decode your post string you may use this couple of methods:
System.Web.HttpUtility.UrlEncode(yourString); // Encode
System.Web.HttpUtility.UrlDecode(yourString); // Decode
You can find more informations about URL manipulation functions here.
Note: If you need to encode/decode an array of string you need to enumerate your collection with a for or foreach statement. Remember that with this kind of cycles you cannot directly change the cycle variable value during the enumeration (so probably you need a temporary storage variable).
At least, to efficiently parse strings, I suggest you to use the System.Text.RegularExpression.Regex class and learn the regex "language".
You can find some example on how to use Regex here; Regex101 site has also a C# code generator that shows you how to translate your regex into code.

C# Pass filename as json parameter- Getting error "Unrecognized escape sequence. "

I want to pass a filepath through JSON. On deserializing I am getting error:
Unrecognized escape sequence. (43): {"Jobtype": "StepBatch","SelectedId": "D:\Input\file1.CATPart"}
I have escaped characters but it still shows error...am I missing something here?
string json = "{\"Jobtype\": \"StepBatch\",\"SelectedId\": \"D:\\Input\\file1.CATPart\"}";
var jsonObj = new JavaScriptSerializer().Deserialize<List<Arguments>>(json);
The problem is that the content of your string at execution time is:
{"Jobtype": "StepBatch","SelectedId": "D:\Input\file1.CATPart"}
That's not valid JSON, because of the backslashes in the value for SelectedId. You'd need the JSON to be:
{"Jobtype": "StepBatch","SelectedId": "D:\\Input\\file1.CATPart"}
so your C# would have to be:
string json = "{\"Jobtype\": \"StepBatch\",\"SelectedId\": \"D:\\\\Input\\\\file1.CATPart\"}";
However, given that you're immediately deserializing the JSON anyway, I'd suggest getting rid of the JSON part entirely, and just creating the Arguments values yourself.
If you need to produce JSON, create the right values directly, and then get JavaScriptSerializer (or preferrably Json.NET) to create the JSON for you, instead of hand-coding it.

Preparing a String to be used in Json

I have a string where I need to use as the body of a JSON object. I know its possible that the data could have quotes in it, so I parse through to add an escape character to those instance of quotes.. like so:
string NewComment = comment.Replace("\"", "\\\"");
However, somehow on some edgecases, a quote still makes it through. I don't know if this is something with UTF or some other issue, But I am trying to find a function that would safely create a json compatible string, I figured there has to be something like this out there, or a regex way of doing so.
Basically a TLDR is how to create a json syntax safe string from a c# string
The simple answer is don't do it this way. What if you have escaped quotes in your string? "Hello \"World\"" would become invalid with such a simple approach: "Hello \\"World\\"". JSON.Net or Newtonsoft are going to save you so many headaches in the long run.

Corrupted JSON HTTP response

I am getting a HTTP request for a website and the content type is JSON. However, I am getting a nested JSON that is a unicode and is causing consistency problems.
Here is an example:
{"key1":"value",
"key2":"value",
"key3":{
u'key31':u'value',
u'key32':u'value'}}
This reminds me of python 2.7 troubles but I am not sure how to fix this JSON. I am using C# to parse it. Everything works correctly until I try to access key3.
The content should be a JSON object type but it is considered rather a value or a string.
Thanks for ya help. Is there a way to fix it if it is actually corrupted or am I parsing it wrongly?
You're correct that this json object is not complete / does not have the correct syntax. You're missing a closing '}' character.
How are you parsing your data? Try taking a look at this documentation.
your json object is not in valid formatted it should be like as folllows
{
"key1":"value",
"key2":"value",
"key3":{
" u'key31'":"u'value'",
"u'key32'":"u'value'"
}
}
by any chance do you get this json from python dump? coz Python's unicode literals are not valid JSON, and neither are single quotes

Dynamic Json deserialization

Deserialize JSON into C# dynamic object?
Following above question, I copy the dynamicJsonDeserilization and trying to use that in my application.
then I try to access the object as
var Data = json.deserilization(jsonstring);
Now, my string is
{"0":{"Name":"C:\\","Type":"Partition","Path":"C:\\"},"1":{"Name":"D:\\","Type":"Partition","Path":"D:\\"},"2":{"Name":"E:\\","Type":"Partition","Path":"E:\\"}}
i.e. I just have an Array on my server which I convert to JSON string and send.
As per code from best answer I should be able to access it as Data.0 but it give "End of Expression expected", Also Data[0] is giving same error. I am not sure how can I use it ? Any help is appreciated. Thanks.
Now, my string is
{"0":{"Name":"C:\","Type":"Partition","Path":"C:\"},"1":{"Name":"D:\","Type":"Partition","Path":"D:\"},"2":{"Name":"E:\","Type":"Partition","Path":"E:\"}}
Your string is indeed not valid JSON due to escaped quotes.
Those C:\ are breaking the parser. You should generate it like this, sending three backslahes:
{"0":{"Name":"C:\\\","Type":"Partition","Path":"C:\\\"} ...

Categories