0

My application uses serverside JavaScript in aspx files on IIS 8 (Windows 2012R2) .
I want to convert a javascript hash to JSON.

My file test.aspx:

<%@language="javascript" Debug="true"%>
<%
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

var header =
{
  "typ": "JWT",
  "alg": "HS256"
};

var str = serializer.Serialize(header);
Response.Write(str);
%>

Result: ["typ","alg"]
Expected result: {"typ":"JWT","alg":"HS256"}

Why does the JavaScriptSerializer not work as expected?

Jeff
  • 736
  • 5
  • 14
  • If I'm understanding you correctly, you expect that serializer.Serialize(header) returns header? – Bardo Jan 11 '17 at 12:24
  • I expect it to return the string `'{"typ":"JWT","alg":"HS256"}'` (added quotes for clarification) – Jeff Jan 11 '17 at 12:50

1 Answers1

0

I'm not sure how well System.Web.Script.Serialization.JavascriptSerializer, which is a server component, will work inside client code.

Probably you'll have better results just using

var str = JSON.stringify(header);

instead of

var str = serializer.Serialize(header);
Bardo
  • 2,470
  • 2
  • 24
  • 42
  • I am running serverside code, this has nothing to do with client code. On the server there is no JSON object: JS1135: Variable 'JSON' has not been declared – Jeff Jan 11 '17 at 13:40
  • The only thing that comes to my mind is that the input you're sending to Serialize is a JS object and maybe this class is not prepared to deal with it (as it surely expects a .NET object). – Bardo Jan 11 '17 at 13:56