Has anyone ever used this and got it working? I'm having real problems because it's telling me there is a JScript error and I'm not sure how to fix it.
Links on this are here to get some background on the product, but it's a JSON parser for classic asp.
Iterating though a JSON return using ASP Xtreme Evolution
I'm sure I had this working the other other day, but now I've come back to it, it's throwing a JScript error, and I can't seem to make it work now.
So, I'm posting JSON to a classic asp page, this is the code I'm using to include the json2.asp page as instructed in all the tutorials:
<%#LANGUAGE="VBSCRIPT"%>
<!--#include file="json2.asp"-->"%>
<% 'json processing details here..
The error it throws is on a line of json2.asp and it's a JScript error. Here is the exact error:
Microsoft JScript compilation error '800a03ea'
Line 765 json2.asp
I believe this is a version of Crockfords json2.js and I think the reason it's in an asp page is so it can use JScript, but it's not progressing for me. Anyone have any idea what I'm talking about that could help me out before I tear all my hair out?!
Let me know if you need more info - many thanks
UPDATE
Here is line 765 (in the middle between the comments)
if (/^[\],:{}\s]*$/.
test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '#').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
j = eval('(' + text + ')');
// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.
return typeof reviver === 'function' ?
walk({'': j}, '') : j;
}
You're not including the right things. You need the whole library available and to include the following files (change your paths appropriately).
<!-- #include file="includes/extlib/axe/base.asp" -->
<!-- #include file="includes/extlib/axe/classes/Parsers/json.class.asp" -->
Then to actually use, you do something like this:
set oJson = new Json
oJson.loadJson(strJSON)
strSomething = oJson.getElement("theElement")
set oJson = nothing
All this taken from working code.
Related
I'm redoing the backend of a very basic framework that connects to a completely customizable frontend. It was originally in PHP but for the refactor have been plodding away in F#. Although it seems like PHP might be the more suited language. But people keep telling me you can do everything in F# and I like the syntax and need to learn and this seemingly simple project has me stumped when it comes to JSON. This is a further fleshed out version of my question yesterday, but it got alot more complex than I thought.
Here goes.
The frontend is basically a collection of HTML files, which are simply loaded in PHP and preg_replace() is used to replace things like [var: varName] or [var: array|key] or the troublesome one: [lang: hello]. That needs to be replaced by a variable defined in a translation dictionary, which is stored as JSON which is also editable by a non-programmer.
I can't change the frontend or the JSON files, and both are designed to be edited by non-programmers so it is very likely that there will be errors, calls to language variables that don't exist etc.
So we might have 2 json files, english.json and french.json
english.json contains:
{
"hello":"Hello",
"bye":"Goodbye"
}
french.json:
{
"hello": "Bonjour",
"duck": "Canard"
//Plus users can add whatever else they want here and expect to be able to use it in a template
}
There is a template that contains
<b>[lang: hello]</b>
<span>Favourite Animal: [lang:duck]</span>
In this case, if the language is set to "english" and english.json is being loaded, that should read:
<b>Hello</b>
<span>Favourite Animal: </span>
Or in French:
<b>Bonjour</b>
<span>Favourite Animal: Canard</span>
We can assume that the json format key: value is always string:string but ideally I'd like to handle string: 'T as well but that might be beyond the scope of this question.
So I need to convert a JSON file (called by dynamic name, which gave F# Data a bit of an issue I couldn't solve last night as it only allowed a static filename as a sample, and since these two files have potential to be different from sample and provided, the type provider doesn't work) to a dictionary or some other collection.
Now inside the template parsing function I need to replace [lang: hello] with something like
let key = "duck"
(*Magic function to convert JSON to usable collection*)
let languageString = convertedJSONCollection.[key] (*And obviously check if containsKey first*)
Which means I need to call the key dynamically, and I couldn't figure out how to do that with the type that FSharp.Data provided.
I have played around with some Thoth as well to some promising results that ended up going nowhere. I avoided JSON.NET because I thought it was paid, but just realised I am mistaken there so might be an avenue to explore
For comparison, the PHP function looks something like this:
function loadLanguage($lang='english){
$json = file_get_contents("$lang.json");
return json_decode($json, true);
}
$key = 'duck';
$langVars = loadLanguage();
$duck = $langVars[$key] || "";
Is there a clean way to do this in F#/.NET? JSON seems really painful to work with in comparison to PHP/Javascript and I'm starting to lose my mind. Am I going to have to write my own parser (which means probably going back to PHP)?
Cheers to all you F# geniuses who know the answer :p
open Thoth.Json.Net
let deserialiseDictionary (s: string) =
s
|> Decode.unsafeFromString (Decode.keyValuePairs Decode.string)
|> Map.ofList
let printDictionary json =
json
|> deserialiseDictionary
|> fun m -> printfn "%s" m.["hello"] // Hello
For the question about 'T the question becomes, what can 'T be? For json it very limited, it can be a number of things, string, json-object, number, bool or json array. What should happen if it is bool or a number?
I'm trying to connect to a REST web service using Delphi 6. I've been able to successfully do this with the code below:
function WSConnect(url: WideString; params: TStringList = nil; method: WideString = 'GET'):WideString;
var
request: XMLHTTP60;
begin
// CreateQueryString below just adds any params passed in to the end of the url
url := url + CreateQueryString(params);
CoInitialize(nil);
request := CoXMLHTTP60.Create;
request.open(method,url,false,'','');
request.send('');
if request.status=200 then
begin
Result := request.responseText;
end else
Result := 'Error: (' + inttostr(request.Status) + ') ' + request.StatusText;
CoUninitialize();
end;
I've pieced together this code from different examples around the net, but I can't find any documentation on CoXMLHTTP60. The code works great, but the current implementation only gives me back a string with the JSON response in it, and I'm struggling to figure out how to pull the properties out of this JSON string in Delphi 6. I've looked at SuperObjects (which people say has problems with Delphi 6 so I didn't try it) and a different project called json4delphi that I couldn't get to compile in Delphi 6 despite it saying it is compatible.
There are also different properties on the CoXMLHTTP60 response object that I believe might get me the values I need. They are:
request.responseBody: OleVariant;
request.responseStream: OleVariant;
request.responseXML: IDispatch;
I would think one of these would provide access to the properties in the JSON, but I can't figure out how to even use them. I'm pretty unfamiliar with IDispatch, once again documentation is difficult to find, and what's there looks very confusing. Some places say to just assign the IDispatch property to an OleVariant and then I can access the properties directly with dot notation, but that doesn't seem to be working either for me, so maybe I'm doing it wrong.
Does anyone have any knowledge on how to pull out the response properties in a CoXMLHTTP60 call?
I'm using re-frame with spec to validate app-db, much like in the todomvc example.
When a user makes an invalid entry, I'm using s/explain-data (in a re-frame interceptor) to return a problems map naming the :predicate which caused validation failure. This predicate is a symbol like project.db/validation-function.
My validation function has metadata which is accessible from the repl using:
(meta #'project.db/validation-function)
The function definition (in the project.db namespace) looks like this:
(defn validation-function
"docstring..."
{:error-message "error message"}
[param]
(function-body...)
The problem is I can't work out how to retrieve the metadata dynamically (working in project.events namespace), for example:
(let [explain-data (s/explain-data spec db)
pred (->> (:cljs.spec.alpha/problems explain-data) first :pred)
msg (what-goes-here? pred)]
msg)
I've tried the following things in place of what-goes-here?:
symbol? gives true
str gives "project.db/validation-function"
meta gives nil
var gives a compile-time error "Unable to resolve var: p1__46744# in this context"
I think the problem is that I'm getting a symbol, but I need the var it refers to, which is where the metadata lives.
I've tried using a macro, but don't really know what I'm doing. This is the closest discussion I could find, but I couldn't work it out.
Help!
In general, you can't do this because vars are not reified in ClojureScript.
From https://clojurescript.org/about/differences#_special_forms :
var notes
Vars are not reified at runtime. When the compiler encounters the var special form it emits a Var instance reflecting compile time metadata. (This satisfies many common static use cases.)
At the REPL, when you evaluate
(meta #'project.db/validation-function)
this is the same as
(meta (var project.db/validation-function))
and when (var project.db/validation-function) is compiled, JavaScript code is emitted to create a cljs.core/Var instance that contains, among other things, the data that you can obtain using meta. If you are curious, the relevant analyzer and compiler code is instructive.
So, if (var project.db/validation-function) (or the reader equivalent #'project.db/validation-function) doesn't exist anywhere in your source code (or indirectly via the use of something like ns-publics) this data won't be available at runtime.
The omission of var reification is a good thing when optimizing for code size. If you enable the :repl-verbose REPL option, you will see that the expression (var project.db/validation-function) emits a significant amount of JavaScript code.
When working with defs at the REPL, the compiler carries sufficient analysis metadata, and things are done—like having evaluations of def forms return the var rather than the value—in the name of constructing an illusion that you are working with reified Clojure vars. But this illusion intentionally evaporates when producing code for production delivery, preserving only essential runtime behavior.
edit: sorry I didn't see that var didn't work for you. Still working on it...
You need to surround the symbol project.db/validation-function with var. This will resolve the symbol to a var.
So what-goes-here? should be
(defn what-goes-here? [pred]
(var pred))
I was under the impression that UTF-8 was the answer to everything :0
Problem: Using Play's idiomatic form handling to go from a web page (basic HTML Text Area Input field) to a MySQL database through the Anorm abstraction layer (so all properly escaped) and then reading the database to gather that data and create an email using the JavaMail API's to send HTML email with alternate characters (accented characters like é for example. (I'd post more but I suspect we might get strange artifacts here as well -- I'll try that in a comment below perhaps)
I can use a moderate set of characters and create a TEXT email (edited via Atom and placed into the stream directly at the code level) and it comes through as an email with all the characters I've chosen in tact.
I have not yet systematically worked through the characters I was just using a relatively random sampling as an initial test.
I place the same set of characters into a text field and try to save them to the database and I can only save about 1 in 5 or less of them.
The errors look like this:
SQLException: Incorrect string value: '\xC4\x93\x0D\x0A\x0D\x0A...' for column 'content' at row 1
I suspect I'm about to learn a ton of new information about either Play and/or UTF-8 or HTML or some part of the chain where this is going off the rails.
My question then is this: Is there an idiomatic Play example of how to handle UTF-8 end to end through Anorm and into Java Mail?
(I think I kinda expected it to be "built-in" but then I expected a LOT more to be baked into the core product as well...)
I want/need both a TEXT and and HTML path for the email portion. (I can write BOTH and they work fine -- the problem is moving alternate characters though the channels as indicated above).
I'm currently seeing if this might be an answer:
https://objectpartners.com/2013/04/24/html-encoding-utf-8-characters/
However presently hitting this roadblock...
How to turn off specific Implicit's in Scala that prevent code from compiling due to overloaded methods?
This appears to be a hopeful candidate -- I am researching it now end to end.
import org.apache.commons.lang3._
def htmlEncode(input: String) = htmlEncode_sb(input).toString
def htmlEncode_sb(input: String, stringBuilder: StringBuilder = new StringBuilder()) = {
stringBuilder.synchronized {
for ((c, i) <- input.zipWithIndex) {
if (CharUtils.isAscii(c)) {
// Encode common HTML equivalent characters
stringBuilder.append(StringEscapeUtils.escapeHtml4(c.toString()))
} else {
// Why isn't this done in escapeHtml4()?
stringBuilder.append(s"""&#${Character.codePointAt(input, i)};""")
}
}
stringBuilder
}
}
In order to get it to work inside Play you'll need this in your build.sbt file
"org.apache.commons" % "commons-lang3" % "3.4",
This blog post lead me to write that code: https://objectpartners.com/2013/04/24/html-encoding-utf-8-characters/
Update: Confirmed that it does work end to end.
Web Page Input as TextArea inside a Form saved to MySQL database escaped by Anorm, reread from database and displayed inside a TextArea on a web page with extended characters (visually) appearing precisely as input.
You'll need to call #Html(htmlContentString) inside the Twirl template to re-render this as the original HTML but the browser (Safari 8.0.7) displayed exactly what I gave it after a round trip to and from the database.
One caveat -- it creates machine readable HTML not human readable HTML. It would be nice if it didn't encode angle brackets and such so it looks more like HTML that we expect. I'm sure a pattern match block will be added next to exclude just that :)
I'm trying to stringify(...) an object in Chrome, and I keep getting a "Converting circular structure to JSON" message, despite the fact that (as far as I know) no such structure exists.
I've been over the code a dozen times and can't find any circular references whatsoever. Is there any way to get Chrome to tell me what it's bitching about beyond this painfully useless error message?
Pardon me if this is too obvious. At the time of writing, I dont know what you have tried.
insert
console.log(the object);
replacing 'the object' with the object you are passing to JSON.stringify()
insert this line before the JSON.stringify call
and look in the console log (shift control J) for the object. In the console log the object will be tagged with a ">" symbol which can be clicked to expand to the fields.
It is complaining about an object that has pointers into itself, like this kind of object:
A = [];
A[0] = A;
JSON.stringify(A); // circular error
You can use dojox.json.ref to find circular references. This code prints json representation of your objectWithCircularReferences:
require(["dojox/json/ref"], function(){
console.log(dojox.json.ref.toJson(objectWithCircularReferences));
});
Any occurence of "$ref" substring in its output to console will help you locate circular references. You can alternatively pipe this json output to global variable ZZZ like this if you wish:
require(["dojox/json/ref"], function(){
window.ZZZ = dojox.json.ref.toJson(objectWithCircularReferences);
});
And of course you need to include dojo library beforehand. In an html file:
<script src="//yandex.st/dojo/1.9.1/dojo/dojo.js"></script>
In firebug console:
include("//yandex.st/dojo/1.9.1/dojo/dojo.js")
In Chrome console:
SCRIPT = document.createElement('script');
SCRIPT.src = '//yandex.st/dojo/1.9.1/dojo/dojo.js';
document.body.appendChild(SCRIPT);