i have i string like
5: "White", 6: "Yellow", 7: "Pink"
i need that string view like this
s={5: "White", 6: "Yellow", 7: "Pink"};
for attach it to select on form
for (var a in myOpts)
{
var t = document.createElement("OPTION");
t.value = a;
t.appendChild(document.createTextNode(myOpts[a]));
selectObj.appendChild(t);
}
If you json_decode your string s, you will get a plain object with 3 owned properties. Then you can loop on those properties with the for..in construct:
var myOpts, s='{5: "White", 6: "Yellow", 7: "Pink"}';
eval('myOpts='+s); // or better, a json parser
for(var a in myOpts) {
if(myOpts.hasOwnProperty(a)) {
// your dom code here
}
}
Your question is a little unclear, however - I'll try to guess what you're saying, cover all cases and give a little added value ;)
I assume that you have a server-side string in a JSP page, who's value is
5: "White", 6: "Yellow", 7: "Pink"
What makes it look like
<%
String data = "5: \"White\", 6: \"Yellow\", 7: \"Pink\"";
%>
And now you want to write it to to the document, so you can for it later on on client-side code.
In that sense - you need to distinguish between few cases.
Although when the server writes it into the response document it is a string - the client code can get this value in different ways. In all of them - the server must write the data in a specific way so that the client can access it, however, the validity rules are different.
Write an object literal
Actually - I think that that's what you're trying to do.
The client code does not get it as a string - but as an object literal.
<script>
var sObjData = {<%= safeJs(data) %>};
</script>
The limits of this choice is that whatever comes from the server code (within the <%%>) and whatever comes from the markup (outside the <%%>) must work together as a valid JavaScript object literal.
There are many things that can break legality of this Object literal - like broken strings, missing commas, missing colons, and so on. Although this is the recommended way - you have to know what you're doing, and I advise you to gap up this knowledge, and your example is a good start.
In your example - this renders to a valid JavaScript Object-Literal, and the problem is not there.
<script>
var sObjData = {5: "White", 6: "Yellow", 7: "Pink"};
</script>
This is a perfectly legal object literal that can be used in for - just the way you do.
It could be that your example is simplification of your case, and the strings that you use may break your execution. Here's how to handle strings from server to client-code:
Write a JavaString string
The limits in this case - is that any character in data string that might break JavaSctipt strinbngs - must be escaped for javascript.
Here I just treat the whole data value, however - bear in mind that you might want to do the same for every values that you put inside this data.
Here's the simplest implementation that explains that's to escape a Java string for JavaScript:
<%!
String safeJs(String data){
return data.replace("\"","\\\"") //why three? two emit a sigle \ and the third escape the "
.replace("'","\\'")
.replace("\n","\\n") //why two? you're not escaping n, your're emitting \ and n
.replace("\r","\\r"); // that will render as escaping for the client code
}
%>
<script>
var sObjData = '<%= safeJs(data) %>';
<script>
This part will assure that you get all the data from the server to the client, and that it will be accessible to the client. From there - it's a matter of your own protocol of delivering data and parsing it on the client.
However, this is not always recommended: If all you're delivering can be formulated as an Object Literal - it is much better - because the Browser handles the parsing for you in a complied code, and gives the scripting code a ready-made object.
Unless you want to parse your own string-protocol, seemingly - its gets the same result to the following, so why bother? better to safeJs your values.
<script>
var sObjData = '<%= safeJs(data) %>';
var oObjData = eval("{" + oObjData + "}");
<script>
Write the string to a content of a TextArea
This is the most robust way of passing strings between server and an HTML client - because the only thing that can break - is if the data string contains a closing tag of TextArea.
A text area is immune to line-breaks, it is immute to quotation marks (single and double), it's sole weakness is it's own closing tag.
Note that replacing the "" with "<textarea>" and "" with "<textarea>".
Assigning an ID to the text area and putting it in style="display:none" assures that it will not bother the UI, and yet be accessible.
<textarea style="display:none" id="txtData"><%=data.replace("</","</")%></textarea>
<script>
var s = document.getElementById("txtData");
</script>
building options in a Select
The DHTML tricks of createElement works, however, I rarely use it, because it's cumbersome, and very low on performance.
However - if you managed to write your Object Literal properly - it should work.
injecting HTML
Instead of creating a select and trying to populate it - it is faster and more reliable to inject it completely into the DOM.
I use the following utility for that:
function getStringBuffer(){
var bfr = [];
bfr.add = function() {
for(var i=0;i<arguments.length;i++) {
this[this.length] = arguments[i];
}
}
bfr.toString = function() { return this.join("") }
return bfr;
}
The wrap in (function(){ and })() creates an anonymous function and executes it instantly - that assures that no variables that are declared for this work will pollute the global scope.
first way - using document.write:
<script>
(function(){
var HTML = getStringBuffer();
var k;
HTML.add("<select id='selectObj'>");
for (k in myOpts) {
HTML.add("<option value='", k, "'>", myOpts[k],"</option>");
}
HTML[HTML.length] = "</select>";
document.write(HTML); //note the overriden toString method that will be called here
})();
</script>
Second way - using innerHTML
You can do the same and instead document.write - use a container tag to mark the place of the select, and inject it there even after the DOM has finished loading.
it's the same as the first way, in one difference: Instead document.write(HTML); -
put a container, say <span id="oSelectPlace"></span> where you want the select to be, and then use
document.getElementById("oSelectPlace").innerHTML = HMTL;
Related
I have an "Invalid character error" while using JS script to extract mails from text that I cannot handle for last 2 days.
I am getting text from web application by using Object cloning and passing it to variable which i will later pass to JS script.
And of course my JS script which I checked and it works:
var args = WScript.Arguments;
var pattern = \w+#\w+.\w;
var result = /pattern/.exec(args);
WScript.StdOut.WriteLine(result);
First and foremost lets break this down it modules and debug them.
.
First Module: Object cloning
Object Cloning is very good to build reliability and this reliability is acheived by careful selection of Properties and in your example you have selected Path,DOMXPath, HTML Tag
Its a good practice to identify the properties which are unique and therefore yield high accuracy and some of these properties depend on the context
For example in a login page some properties include:
Priority 1: Path, HTML ID, InnerText
Priority 2: DOMXPath, HTMLValue
You may chose to add properties that you think may be unique to your context
Does strResult give you the expected value ? If yes, lets proceed
Second Module: Run Script
Accepts 2 Parameters $strResult$ and $mail$
And of course my JS script which I checked and it works:
and you have confirmed the JS module also runs fine
If you have verified the results of the first 2 modules, I think there could be an Invalid character somewhere in the script, parameters, check the regular expressions used. Shouldn't the pattern be enclosed in string " " ??
=====================
EDIT:
I wanted to recreate the issue and give you the desired result but I do not know your intended input and output for Javascript. However to the best of my understanding of your javascript, I have compiled and executed this script in Automation Anywhere and works perfect.
JavaScript
var args = WScript.Arguments;
if (args.length > 0)
{
var val=0;
var str=args.item(0);
var ary = str.split(",");
//WScript.Echo(ary.length);
// for loop in case there are multiple parameters passed
for (var i=0; i < ary.length; i++)
{
//Takes the input passed as parameter
var input = (ary[i]);
// Uses the Match() Method to look for an email address in input string
var result = input.match(/\w+#\w+\.com/);
//returns the email address
}
WScript.StdOut.WriteLine(result);
}
OR
//Takes the input passed as parameter
var input = (ary[i]);
//Declares the pattern used
var pattern = /\w+#\w+\.com/
// Uses the Exec() Method to look for a match
var result = pattern.exec(input);
//returns the email address
Run Script
Input Parameter
Output Parameter
Can someone format the code below so that I can set srcript variables with c# code using razor?
The below does not work, i've got it that way to make is easy for someone to help.
#{int proID = 123; int nonProID = 456;}
<script type="text/javascript">
#{
<text>
var nonID =#nonProID;
var proID= #proID;
window.nonID = #nonProID;
window.proID=#proID;
</text>
}
</script>
I am getting a design time error
You should take a look at the output that your razor page is resulting. Actually, you need to know what is executed by server-side and client-side. Try this:
#{
int proID = 123;
int nonProID = 456;
}
<script>
var nonID = #nonProID;
var proID = #proID;
window.nonID = #nonProID;
window.proID = #proID;
</script>
The output should be like this:
Depending what version of Visual Studio you are using, it point some highlights in the design-time for views with razor.
Since razor syntax errors can become problematic while you're working on the view, I totally get why you'd want to avoid them. Here's a couple other options.
<script type="text/javascript">
// #Model.Count is an int
var count = '#Model.Count';
var countInt = parseInt('#Model.ActiveLocsCount');
</script>
The quotes act as delimiters, so the razor parser is happy. But of course your C# int becomes a JS string in the first statement. For purists, the second option might be better.
If somebody has a better way of doing this without the razor syntax errors, in particular maintaining the type of the var, I'd love to see it!
This is how I solved the problem:
#{int proID = 123; int nonProID = 456;}
<script type="text/javascript">
var nonID = Number(#nonProID);
var proID = Number(#proID);
</script>
It is self-documenting and it doesn't involve conversion to and from text.
Note: be careful to use the Number() function not create new Number() objects - as the exactly equals operator may behave in a non-obvious way:
var y = new Number(123); // Note incorrect usage of "new"
var x = new Number(123);
alert(y === 123); // displays false
alert(x == y); // displays false
I've seen several approaches to working around the bug, and I ran some timing tests to see what works for speed (http://jsfiddle.net/5dwwy/)
Approaches:
Direct assignment
In this approach, the razor syntax is directly assigned to the variable. This is what throws the error. As a baseline, the JavaScript speed test simply does a straight assignment of a number to a variable.
Pass through `Number` constructor
In this approach, we wrap the razor syntax in a call to the `Number` constructor, as in `Number(#ViewBag.Value)`.
ParseInt
In this approach, the razor syntax is put inside quotes and passed to the `parseInt` function.
Value-returning function
In this approach, a function is created that simply takes the razor syntax as a parameter and returns it.
Type-checking function
In this approach, the function performs some basic type checking (looking for null, basically) and returns the value if it isn't null.
Procedure:
Using each approach mentioned above, a for-loop repeats each function call 10M times, getting the total time for the entire loop. Then, that for-loop is repeated 30 times to obtain an average time per 10M actions. These times were then compared to each other to determine which actions were faster than others.
Note that since it is JavaScript running, the actual numbers other people receive will differ, but the importance is not in the actual number, but how the numbers compare to the other numbers.
Results:
Using the Direct assignment approach, the average time to process 10M assignments was 98.033ms. Using the Number constructor yielded 1554.93ms per 10M. Similarly, the parseInt method took 1404.27ms. The two function calls took 97.5ms for the simple function and 101.4ms for the more complex function.
Conclusions:
The cleanest code to understand is the Direct assignment. However, because of the bug in Visual Studio, this reports an error and could cause issues with Intellisense and give a vague sense of being wrong.
The fastest code was the simple function call, but only by a slim margin. Since I didn't do further analysis, I do not know if this difference has a statistical significance. The type-checking function was also very fast, only slightly slower than a direct assignment, and includes the possibility that the variable may be null. It's not really practical, though, because even the basic function will return undefined if the parameter is undefined (null in razor syntax).
Parsing the razor value as an int and running it through the constructor were extremely slow, on the order of 15x slower than a direct assignment. Most likely the Number constructor is actually internally calling parseInt, which would explain why it takes longer than a simple parseInt. However, they do have the advantage of being more meaningful, without requiring an externally-defined (ie somewhere else in the file or application) function to execute, with the Number constructor actually minimizing the visible casting of an integer to a string.
Bottom line, these numbers were generated running through 10M iterations. On a single item, the speed is incalculably small. For most, simply running it through the Number constructor might be the most readable code, despite being the slowest.
#{
int proID = 123;
int nonProID = 456;
}
<script>
var nonID = '#nonProID';
var proID = '#proID';
window.nonID = '#nonProID';
window.proID = '#proID';
</script>
One of the easy way is:
<input type="hidden" id="SaleDateValue" value="#ViewBag.SaleDate" />
<input type="hidden" id="VoidItem" value="#Model.SecurityControl["VoidItem"].ToString()" />
And then get the value in javascript:
var SaleDate = document.getElementById('SaleDateValue').value;
var Item = document.getElementById('VoidItem').value;
I found a very clean solution that allows separate logic and GUI:
in your razor .cshtml page try this:
<body id="myId" data-my-variable="myValue">
...your page code here
</body>
in your .js file or .ts (if you use typeScript) to read stored value from your view put some like this (jquery library is required):
$("#myId").data("my-variable")
Not so much an answer as a cautionary tale: this was bugging me as well - and I thought I had a solution by pre-pending a zero and using the #(...) syntax. i.e your code would have been:
var nonID = 0#(nonProID);
var proID = 0#(proID);
Getting output like:
var nonId = 0123;
What I didn't realise was that this is how JavaScript (version 3) represents octal/base-8 numbers and is actually altering the value. Additionally, if you are using the "use strict"; command then it will break your code entirely as octal numbers have been removed.
I'm still looking for a proper solution to this.
It works if you do something like this:
var proID = #proID + 0;
Which produces code that is something like:
var proID = 4 + 0;
A bit odd for sure, but no more fake syntax errors at least.
Sadly the errors are still reported in VS2013, so this hasn't been properly addressed (yet).
I've been looking into this approach:
function getServerObject(serverObject) {
if (typeof serverObject === "undefined") {
return null;
}
return serverObject;
}
var itCameFromDotNet = getServerObject(#dotNetObject);
To me this seems to make it safer on the JS side... worst case you end up with a null variable.
This should cover all major types:
public class ViewBagUtils
{
public static string ToJavascriptValue(dynamic val)
{
if (val == null) return "null";
if (val is string) return val;
if (val is bool) return val.ToString().ToLower();
if (val is DateTime) return val.ToString();
if (double.TryParse(val.ToString(), out double dval)) return dval.ToString();
throw new ArgumentException("Could not convert value.");
}
}
And in your .cshtml file inside the <script> tag:
#using Namespace_Of_ViewBagUtils
const someValue = #ViewBagUtils.ToJavascriptValue(ViewBag.SomeValue);
Note that for string values, you'll have to use the #ViewBagUtils expression inside single (or double) quotes, like so:
const someValue = "#ViewBagUtils.ToJavascriptValue(ViewBag.SomeValue)";
I use a very simple function to solve syntax errors in body of JavaScript codes that mixed with Razor codes ;)
function n(num){return num;}
var nonID = n(#nonProID);
var proID= n(#proID);
This sets a JavaScript var for me directly from a web.config defined appSetting..
var pv = '#System.Web.Configuration.WebConfigurationManager.AppSettings["pv"]';
With
var jsVar = JSON.parse(#Html.Raw(Json.Serialize(razorObject)));
you can parse any razor object into a JavaScript object.
It's long but universal
Can someone format the code below so that I can set srcript variables with c# code using razor?
The below does not work, i've got it that way to make is easy for someone to help.
#{int proID = 123; int nonProID = 456;}
<script type="text/javascript">
#{
<text>
var nonID =#nonProID;
var proID= #proID;
window.nonID = #nonProID;
window.proID=#proID;
</text>
}
</script>
I am getting a design time error
You should take a look at the output that your razor page is resulting. Actually, you need to know what is executed by server-side and client-side. Try this:
#{
int proID = 123;
int nonProID = 456;
}
<script>
var nonID = #nonProID;
var proID = #proID;
window.nonID = #nonProID;
window.proID = #proID;
</script>
The output should be like this:
Depending what version of Visual Studio you are using, it point some highlights in the design-time for views with razor.
Since razor syntax errors can become problematic while you're working on the view, I totally get why you'd want to avoid them. Here's a couple other options.
<script type="text/javascript">
// #Model.Count is an int
var count = '#Model.Count';
var countInt = parseInt('#Model.ActiveLocsCount');
</script>
The quotes act as delimiters, so the razor parser is happy. But of course your C# int becomes a JS string in the first statement. For purists, the second option might be better.
If somebody has a better way of doing this without the razor syntax errors, in particular maintaining the type of the var, I'd love to see it!
This is how I solved the problem:
#{int proID = 123; int nonProID = 456;}
<script type="text/javascript">
var nonID = Number(#nonProID);
var proID = Number(#proID);
</script>
It is self-documenting and it doesn't involve conversion to and from text.
Note: be careful to use the Number() function not create new Number() objects - as the exactly equals operator may behave in a non-obvious way:
var y = new Number(123); // Note incorrect usage of "new"
var x = new Number(123);
alert(y === 123); // displays false
alert(x == y); // displays false
I've seen several approaches to working around the bug, and I ran some timing tests to see what works for speed (http://jsfiddle.net/5dwwy/)
Approaches:
Direct assignment
In this approach, the razor syntax is directly assigned to the variable. This is what throws the error. As a baseline, the JavaScript speed test simply does a straight assignment of a number to a variable.
Pass through `Number` constructor
In this approach, we wrap the razor syntax in a call to the `Number` constructor, as in `Number(#ViewBag.Value)`.
ParseInt
In this approach, the razor syntax is put inside quotes and passed to the `parseInt` function.
Value-returning function
In this approach, a function is created that simply takes the razor syntax as a parameter and returns it.
Type-checking function
In this approach, the function performs some basic type checking (looking for null, basically) and returns the value if it isn't null.
Procedure:
Using each approach mentioned above, a for-loop repeats each function call 10M times, getting the total time for the entire loop. Then, that for-loop is repeated 30 times to obtain an average time per 10M actions. These times were then compared to each other to determine which actions were faster than others.
Note that since it is JavaScript running, the actual numbers other people receive will differ, but the importance is not in the actual number, but how the numbers compare to the other numbers.
Results:
Using the Direct assignment approach, the average time to process 10M assignments was 98.033ms. Using the Number constructor yielded 1554.93ms per 10M. Similarly, the parseInt method took 1404.27ms. The two function calls took 97.5ms for the simple function and 101.4ms for the more complex function.
Conclusions:
The cleanest code to understand is the Direct assignment. However, because of the bug in Visual Studio, this reports an error and could cause issues with Intellisense and give a vague sense of being wrong.
The fastest code was the simple function call, but only by a slim margin. Since I didn't do further analysis, I do not know if this difference has a statistical significance. The type-checking function was also very fast, only slightly slower than a direct assignment, and includes the possibility that the variable may be null. It's not really practical, though, because even the basic function will return undefined if the parameter is undefined (null in razor syntax).
Parsing the razor value as an int and running it through the constructor were extremely slow, on the order of 15x slower than a direct assignment. Most likely the Number constructor is actually internally calling parseInt, which would explain why it takes longer than a simple parseInt. However, they do have the advantage of being more meaningful, without requiring an externally-defined (ie somewhere else in the file or application) function to execute, with the Number constructor actually minimizing the visible casting of an integer to a string.
Bottom line, these numbers were generated running through 10M iterations. On a single item, the speed is incalculably small. For most, simply running it through the Number constructor might be the most readable code, despite being the slowest.
#{
int proID = 123;
int nonProID = 456;
}
<script>
var nonID = '#nonProID';
var proID = '#proID';
window.nonID = '#nonProID';
window.proID = '#proID';
</script>
One of the easy way is:
<input type="hidden" id="SaleDateValue" value="#ViewBag.SaleDate" />
<input type="hidden" id="VoidItem" value="#Model.SecurityControl["VoidItem"].ToString()" />
And then get the value in javascript:
var SaleDate = document.getElementById('SaleDateValue').value;
var Item = document.getElementById('VoidItem').value;
I found a very clean solution that allows separate logic and GUI:
in your razor .cshtml page try this:
<body id="myId" data-my-variable="myValue">
...your page code here
</body>
in your .js file or .ts (if you use typeScript) to read stored value from your view put some like this (jquery library is required):
$("#myId").data("my-variable")
Not so much an answer as a cautionary tale: this was bugging me as well - and I thought I had a solution by pre-pending a zero and using the #(...) syntax. i.e your code would have been:
var nonID = 0#(nonProID);
var proID = 0#(proID);
Getting output like:
var nonId = 0123;
What I didn't realise was that this is how JavaScript (version 3) represents octal/base-8 numbers and is actually altering the value. Additionally, if you are using the "use strict"; command then it will break your code entirely as octal numbers have been removed.
I'm still looking for a proper solution to this.
It works if you do something like this:
var proID = #proID + 0;
Which produces code that is something like:
var proID = 4 + 0;
A bit odd for sure, but no more fake syntax errors at least.
Sadly the errors are still reported in VS2013, so this hasn't been properly addressed (yet).
I've been looking into this approach:
function getServerObject(serverObject) {
if (typeof serverObject === "undefined") {
return null;
}
return serverObject;
}
var itCameFromDotNet = getServerObject(#dotNetObject);
To me this seems to make it safer on the JS side... worst case you end up with a null variable.
This should cover all major types:
public class ViewBagUtils
{
public static string ToJavascriptValue(dynamic val)
{
if (val == null) return "null";
if (val is string) return val;
if (val is bool) return val.ToString().ToLower();
if (val is DateTime) return val.ToString();
if (double.TryParse(val.ToString(), out double dval)) return dval.ToString();
throw new ArgumentException("Could not convert value.");
}
}
And in your .cshtml file inside the <script> tag:
#using Namespace_Of_ViewBagUtils
const someValue = #ViewBagUtils.ToJavascriptValue(ViewBag.SomeValue);
Note that for string values, you'll have to use the #ViewBagUtils expression inside single (or double) quotes, like so:
const someValue = "#ViewBagUtils.ToJavascriptValue(ViewBag.SomeValue)";
I use a very simple function to solve syntax errors in body of JavaScript codes that mixed with Razor codes ;)
function n(num){return num;}
var nonID = n(#nonProID);
var proID= n(#proID);
This sets a JavaScript var for me directly from a web.config defined appSetting..
var pv = '#System.Web.Configuration.WebConfigurationManager.AppSettings["pv"]';
With
var jsVar = JSON.parse(#Html.Raw(Json.Serialize(razorObject)));
you can parse any razor object into a JavaScript object.
It's long but universal
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JSON pretty print using JavaScript
I'd like to display my raw JSON data on a HTML page just as JSONview does. For example, my raw json data is:
{
"hey":"guy",
"anumber":243,
"anobject":{
"whoa":"nuts",
"anarray":[
1,
2,
"thr<h1>ee"
],
"more":"stuff"
},
"awesome":true,
"bogus":false,
"meaning":null,
"japanese":"明日がある。",
"link":"http://jsonview.com",
"notLink":"http://jsonview.com is great"
}
It comes from http://jsonview.com/, and what I want to achieve is like http://jsonview.com/example.json if you use Chrome and have installed the JSONView plugin.
I've tried but failed to understand how it works. I'd like to use a JS script (CSS to highlight) to custom format my raw JSON data which is retrieved by ajax and finally put it on a HTML page in any position like into a div element. Are there any existing JS libraries that can achieve this? Or how to do it?
I think all you need to display the data on an HTML page is JSON.stringify.
For example, if your JSON is stored like this:
var jsonVar = {
text: "example",
number: 1
};
Then you need only do this to convert it to a string:
var jsonStr = JSON.stringify(jsonVar);
And then you can insert into your HTML directly, for example:
document.body.innerHTML = jsonStr;
Of course you will probably want to replace body with some other element via getElementById.
As for the CSS part of your question, you could use RegExp to manipulate the stringified object before you put it into the DOM. For example, this code (also on JSFiddle for demonstration purposes) should take care of indenting of curly braces.
var jsonVar = {
text: "example",
number: 1,
obj: {
"more text": "another example"
},
obj2: {
"yet more text": "yet another example"
}
}, // THE RAW OBJECT
jsonStr = JSON.stringify(jsonVar), // THE OBJECT STRINGIFIED
regeStr = '', // A EMPTY STRING TO EVENTUALLY HOLD THE FORMATTED STRINGIFIED OBJECT
f = {
brace: 0
}; // AN OBJECT FOR TRACKING INCREMENTS/DECREMENTS,
// IN PARTICULAR CURLY BRACES (OTHER PROPERTIES COULD BE ADDED)
regeStr = jsonStr.replace(/({|}[,]*|[^{}:]+:[^{}:,]*[,{]*)/g, function (m, p1) {
var rtnFn = function() {
return '<div style="text-indent: ' + (f['brace'] * 20) + 'px;">' + p1 + '</div>';
},
rtnStr = 0;
if (p1.lastIndexOf('{') === (p1.length - 1)) {
rtnStr = rtnFn();
f['brace'] += 1;
} else if (p1.indexOf('}') === 0) {
f['brace'] -= 1;
rtnStr = rtnFn();
} else {
rtnStr = rtnFn();
}
return rtnStr;
});
document.body.innerHTML += regeStr; // appends the result to the body of the HTML document
This code simply looks for sections of the object within the string and separates them into divs (though you could change the HTML part of that). Every time it encounters a curly brace, however, it increments or decrements the indentation depending on whether it's an opening brace or a closing (behaviour similar to the space argument of 'JSON.stringify'). But you could this as a basis for different types of formatting.
Note that the link you provided does is not an HTML page, but rather a JSON document. The formatting is done by the browser.
You have to decide if:
You want to show the raw JSON (not an HTML page), as in your example
Show an HTML page with formatted JSON
If you want 1., just tell your application to render a response body with the JSON, set the MIME type (application/json), etc.
In this case, formatting is dealt by the browser (and/or browser plugins)
If 2., it's a matter of rendering a simple minimal HTML page with the JSON where you can highlight it in several ways:
server-side, depending on your stack. There are solutions for almost every language
client-side with Javascript highlight libraries.
If you give more details about your stack, it's easier to provide examples or resources.
EDIT: For client side JS highlighting you can try higlight.js, for instance.
JSON in any HTML tag except <script> tag would be a mere text. Thus it's like you add a story to your HTML page.
However, about formatting, that's another matter. I guess you should change the title of your question.
Take a look at this question. Also see this page.
I am working on an ASP classic project where I have implemented the JScript JSON class found here. It is able to interop with both VBScript and JScript and is almost exactly the code provided at json.org. I am required to use VBScript for this project by the manager of my team.
It works very well on primitives and classes defined within ASP. But I have need for Dictionary objects which from my knowledge are only available through COM interop. (via Server.CreateObject("Scripting.Dictionary")) I have the following class which represents a product: (ProductInfo.class.asp)
<%
Class ProductInfo
Public ID
Public Category
Public PriceUS
Public PriceCA
Public Name
Public SKU
Public Overview
Public Features
Public Specs
End Class
%>
The Specs property is a Dictionary of key:value pairs. Here's how I'm serializing it: (product.asp)
<%
dim oProd
set oProd = new ProductInfo
' ... fill in properties
' ... output appropriate headers and stuff
Response.write( JSON.stringify( oProd ) )
%>
When I pass an instance of ProductInfo to JSON.Stringify (as seen above) I get something like the following:
{
"id": "1547",
"Category": {
"id": 101,
"Name": "Category Name",
"AlternateName": "",
"URL": "/category_name/",
"ParentCategoryID": 21
},
"PriceUS": 9.99,
"PriceCA": 11.99,
"Name": "Product Name",
"SKU": 3454536,
"Overview": "Lorem Ipsum dolor sit amet..",
"Features": "Lorem Ipsum dolor sit amet..",
"Specs": {}
}
As you can see, the Specs property is an empty object. I believe that the JSON stringify method knows that the Specs property is an object, so it appends the {} to the JSON string around the stringified output. Which in this case is an empty string. What I expect it to show, however is not an empty object. See below:
"Specs": {
"foo":"bar",
"baz":1,
"etc":"..."
}
I believe the problem area of the JSON library is here: (json2.asp)
// Otherwise, iterate through all of the keys in the object.
for (k in value) {
if (Object.hasOwnProperty.call(value, k)) {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
I postulate that the problem with the above code is that it assumes that all objects inherit from the Object class. (The one that provides hasOwnProperty) However I think that it's likely that COM objects don't inherit from the Object class — or at least the same Object class. Or at least don't implement whatever interface is required to do for ... in on them.
Update: While I feel it is irrelevant for the question to be answered — I expect some sort of web client to request (via http) the JSON representation of this object or a collection of this object.
tl;dr The question: What should I do to make it so that the Scripting.Dictionary can be output properly as JSON instead of failing and returning just an empty string? Do I need to 'reinvent the wheel' and write my own Dictionary class in VBScript that does act as a normal object in ASP?
Javascript’s for...in construct (which is used in the JSON serializer you refer to) only works on native JS objects. To enumerate a Scripting.Dictionary’s keys, you need to use an Enumerator object, which will enumerate the keys of the Dictionary.
Now the JSON.stringify method has a nifty way of allowing custom serialization, by checking for the presence of a toJSON method on each property. Unfortunately, you can’t tack new methods on existing COM objects the way you can on native JS objects, so that’s a no-go.
Then there’s the custom stringifier function that can be passed as second argument to the stringify method call. That function will be called for each object that needs to be stringified, even for each nested object. I think that could be used here.
One problem is that (AFAIK) JScript is unable to differentiate VBScript types on its own. To JScript, any COM or VBScript object has typeof === 'object'. The only way I know of getting that information across, is defining a VBS function that will return the type name.
Since the execution order for classic ASP files is as follows:
<script> blocks with non-default script languages (in your case, JScript)
<script> blocks with the default script language (in your case, VBScript)
<% ... %> blocks, using the default script language (in your case, VBScript)
The following could work — but only when the JSON.stringify call is done within <% ... %> brackets, since that’s the only time when both JScript and VBScript <script> sections would both have been parsed and executed.
The final function call would be this:
<%
Response.Write JSON.stringify(oProd, vbsStringifier)
%>
In order to allow JScript to check the type of a COM object, we'd define a VBSTypeName function:
<script language="VBScript" runat="server">
Function VBSTypeName(Obj)
VBSTypeName = TypeName(Obj)
End Function
</script>
And here we have the full implementation of the vbsStringifier that is passed along as second parameter to JSON.stringify:
<script language="JScript" runat="server">
function vbsStringifier(holder, key, value) {
if (VBSTypeName(value) === 'Dictionary') {
var result = '{';
for(var enr = new Enumerator(value); !enr.atEnd(); enr.moveNext()) {
key = enr.item();
result += '"' + key + '": ' + JSON.stringify(value.Item(key));
}
result += '}';
return result;
} else {
// return the value to let it be processed in the usual way
return value;
}
}
</script>
Of course, switching back and forth between scripting engines isn’t very efficient (i.e. calling a VBS function from JS and vice versa), so you probably want to try to keep that to a minimum.
Also note that I haven’t been able to test this, since I no longer have IIS on my machine. The basic principle should work, I’m not 100% certain of the possibility to pass a JScript function reference from VBScript. You might have to write a small custom wrapper function for the JSON.stringify call in JScript:
<script runat="server" language="JScript">
function JSONStringify(object) {
return JSON.stringify(object, vbsStringifier);
}
</script>
after which you can simply adjust the VBScript call:
<%
Response.Write JSONStringify(oProd)
%>
I ended up writing a function to serialize the Dictionary type myself. Unfortunately, you'll have to go in and do a find & replace on any failed dictionary serializations. ({}) I haven't the time to figure out an automated way to do this. You're welcome to fork it on BitBucket.
Function stringifyDictionary( key, value, sp )
dim str, val
Select Case TypeName( sp )
Case "String"
sp = vbCrLf & sp
Case "Integer"
sp = vbCrLf & Space(sp)
Case Else
sp = ""
End Select
If TypeName( value ) = "Dictionary" Then
str = """" & key & """:{" & sp
For Each k in value
val = value.Item(k)
If Not Right(str, 1+len(sp)) = "{" & sp And Not Right(str, 1+len(sp)) = "," & sp Then
str = str & "," & sp
End If
str = str & """" & k & """: "
If TypeName( val ) = "String" Then
If val = "" Then
str = str & "null"
Else
str = str & """" & escapeJSONString( val ) & """"
End If
Else
str = str & CStr( val )
End If
Next
str = str & sp & "}"
stringifyDictionary = str
Else
stringifyDictionary = value
End If
End Function
Function escapeJSONString( str )
escapeJSONString = replace(replace(str, "\", "\\"), """", "\""")
End Function
This was written as a function to use with JSON.stringify's replace argument (2nd arg). However you cannot pass a VBScript function as an argument. (From my experience) If you were to rewrite this function in JScript you could use it when you're calling JSON.stringify to ensure that Dictionaries do get rendered properly. See the readme on BitBucket for more on that. Here's how I implemented it:
dim spaces: spaces = 2
dim prodJSON: prodJSON = JSON.stringify( oProduct, Nothing, spaces)
prodJSON = replace(prodJSON, """Specs"": {}", stringifyDictionary("Specs", oProduct.Specs, spaces * 2))
Known issues:
The closing } for the Dictionary serialization will be the same number of indentations as the properties it contains. I didn't have time to figure out how to deal with that without adding another argument which I don't want to do.
JSON does not inherently encode any type information at all. What JSON enables you to represent is an arbitrary data structure involving either an object or an array of values. Any such object may have an arbitrary number of named properties such that the names are strings and the values are either the constant null, the constants true or false, numbers, strings, objects, or arrays of values.
How such a data structure is realized in any given programming language runtime is your problem :-) For example, when de-serializing JSON into Java, one might use ArrayList instances for arrays, HashMap instances for objects, and native types for simpler values. However, it might be that you really want the objects to be some particular type of Java bean class. To do that, the JSON parser involved would have to be somehow guided as to what sort of objects to instantiate. Exactly how that works depends on the JSON parser and its APIs.
(edit — when I said "no type information at all", I meant for "object" values; clearly booleans, strings, and numbers have obvious types.)