I need to create something like the following JSON entity:
{
"foo": function() { *some code* }
}
Can any of the common JSON libraries (json, jsonb, aeron etc.) easily achieve that?
I didn't find a way to tell the library not to quote the function part when encoding.
Thanks,
p.s. I understand the reason for not allowing such usage is to enforce correct syntax, but I'm willing to take that risk here.
That is not a JSON entity, but a JavaScript object. JSON has no concept of functions.
The only way to have a function encoded in JSON is indeed to encode it in a string:
{ "foo": "function() { return \"Hello, World\" }" }
When you want to execute that function in JavaScript, you'll have to eval the string:
var jsonObj = JSON.parse('{ "foo": "function() {return \\"Hello, World\\";}" }');
var jfoo = eval('(' + jsonObj.foo + ')');
alert(jfoo()); // Shows a dialog box "Hello, World"
Note that this allows the source of the JSON to execute arbitrary JavaScript in the context of your website or application. Therefore, you should transfer data instead of functions whenever possible, and make sure not to eval code from untrusted sources.
Related
I'm working on my first Terraform project and I'm looking for the best way to stringify a JSON object. The resource I'm defining has a parameter that expects a JSON string. JSON structure is:
"document": {
"tag": "String Title",
"response": "There's a string response and perhaps a price like $[XX.XX]."
}
}
I don't think jsonencode or jsondecode do this. I could stringify them in advance but that isn't scalable in this case. I wasn't sure if I could do this with JavaScript or another language alongside Terraform, or if there's a function in HCL that will do it.
jsonencode in Terraform is exactly equivalent to JSON.stringify with only one argument in JavaScript.
For example, if you need to assign a string containing a JSON object to an argument called something_json, you could do that like this:
something_json = jsonencode({
document = {
tag = "String Title"
response = "There's a string response and perhaps a price like $[XX.XX]."
}
})
The above would set something_json to a minified version of the following JSON:
{
"document": {
"tag": "String Title",
"response": "There's a string response and perhaps a price like $[XX.XX]."
}
}
Terraform does not have an equivalent of the optional replacer and space arguments in JavaScript's JSON.stringify:
An equivalent of replacer isn't needed in Terraform because all possible values in the Terraform language have a defined JSON equivalent as described in the table in the jsonencode documentation.
space is for generating non-minified JSON; Terraform does not offer any way to do this because it is focused on generating JSON for machine consumption and so prefers to generate the most compact representation possible.
below my json :
"temperature": {
"level": 8,
"format": function (value) {
return value + ' (C°)';
},
"minimum": null,
...
...
}
My goal is to write key format, I have try this but without much conviction...
package require rl_json
namespace import rl_json::json
set rj "{}"
set s1 {function (value) {
return value + ' (C°)';
}
}
json set rj temperature [json object [list level {number 8} format [json template {{"~L:s1"}}] minimum {null}]]
Error parsing JSON value: Expecting : after object key at offset 8
What you are trying to produce is not (partial) JSON, as defined, but rather general Javascript. As such, you cannot reasonably expect JSON-specific tooling (such as rl_json) to work with it. It is usually better to keep your JSON and your Javascript separated, with the data in JSON (including any dynamic generation) and your Javascript as a static artefact (or generated from something like Typescript). Mixing code and dynamic generation requires great care to get right; it is usually better to try to write things so you don't need to be that careful!
If you must do this defintely-not-advised thing, use something like subst or format to inject the variable parts (which you can generate with rl_json) in the overall string. No code for that from me: my advice is don't do that.
I have a JSON object which I would like to templatize in lua. For example:
{
"type":"email",
"version":"1.0",
"account":"%emailId%"
}
I would like to substitute the %emailId% with a list of e-mail ids. Is there a templatization support for JSON in lua?
No, there is no built-in support for either JSON or templating in the core Lua language or libraries. There are a number of JSON modules available, but I'm not sure whether any of them have template support. You might have to write a templating function yourself, but it probably won't be too hard - it's just a matter of iterating over all the string values with the JSON module and using string.gsub on them.
Though it isn't intended for JSON you can use lua-resty-template.
user.json:
{ "user": "{{username}}" }
lua-code:
local template = require "resty.template"
local result = template.compile("user.json")({ username = "someone" })
print(result);
result:
{ "user": "someone" }
I read my json file using http and cordova file readAsText functions.
http request returns an object which is ok.
cordova file readAsText function return 'string' which contain extra "r\n\" symbols. This make it impossible to use JSON.parse(evt.target.result)
function readJson(absPath, success, failed){
window.resolveLocalFileSystemURL(absPath, function (entry) {
entry.file(function (file) {
var reader = new FileReader();
reader.onloadend = function (evt) {
success(evt.target.result);
};
reader.readAsText(file);
}, failed);
}, failed);
}
readJson(cordova.file.dataDirectory + 'my.json', function(res){
console.log(JSON.parse(res)); //here I've got an parsing error due to presence of r\n\ symbols
}, failed );
How to read JSON files using cordova?
UPDATE:
funny thing that the following works:
a = '{\r\n"a":"1",\r\n"b":"2"\r\n}';
b = JSON.parse(a);
so the problem not only with \r\n... there is something else that is added by cordova readAsText
UPDATE2
as a workaround I use now var object = eval("(" + res + ")")
Still search for a common way to load json objects...
No one has answered this and I just had to solve it for my project, so I will post my solution.
The readAsText method outputs a string, so you CAN actually run a replace on it, but what you need to do is use a RegExp to find the newline character. here's my solution:
var sanitizerRegex = new RegExp(String.fromCharCode(10), 'g');
var sanitizedData = JSON.parse(result.replace(sanitizerRegex, ''));
I've used the String method fromCharCode to get the specific newline character and the "g" flag to match all instances in the entire string. The problem with your string solution is that you can't do a string replace using the characters for backslash and "n" because the issue is the actual new line character, which is merely represented as "\n".
I do not know the reason JSON.parse can't handle the newline character, or why the file plugin introduces this problem, but this solution seems to work for me.
Also, NEVER use eval like this if you can avoid it, especially on input from a source like a JSON file. Even in a cordova app, using eval is potentially very unsafe.
I found out the solution after debug deeply. readAsText function returned text has one more letter at the first position of text.
Example:
{"name":"John"} => ?{"name":"John"} (?: API didn't return ?, just one string)
I confirmed this with length of result, so we need to use substr(1) before parse JSON.
fileContent = fileContent.substr(1);
var jData = jQuery.parseJSON(fileContent);
this is my json format
({"message":{"success":true,"result":[{"lead_no":"LEA13","lastname":"Developer","firstname":"PHP","company":"Dummies","email":"nandhajj#gmail.com","id":"10x132"},{"lead_no":"LEA14","lastname":"Venu","firstname":"Yatagiri","company":"Rsalesarm","email":"veve#jajs.com","id":"10x133"},{"lead_no":"LEA4","lastname":"Jones","firstname":"Barbara","company":"Vtigercrm inc","email":"barbara_jones#company.com","id":"10x35"},{"lead_no":"LEA1","lastname":"Smith","firstname":"Mary","company":"Vtiger","email":"mary_smith#company.com","id":"10x32"}]}})
i am trying to retrieve the whole json result values using the following snippet
if (xmlHttp.readyState==4)
{
alert(xmlHttp.status);
if(xmlHttp.status==200)
{
alert("hi");
var jsondata=eval("("+xmlHttp.responseText+")") //retrieve result as an JavaScript object
jsonOutput=jsondata.result;
alert(jsonOutput);
InitializeLeadStorage()
}
}
my alert (hi ) is displayed but the alert(jsonOutput); is undefined , please help me if you could find any mistake
jsonOutput = jsondata.message.result;
result lives on message - it is not a top-level item in the JSON. With things like this, console.log() the JSON and you can check the path to the bit you want.
Also
your variable is global
there are better ways of parsing your JSON. If you don't care about old IEs, you can use the ECMA5 JSON.parse(), else use jQuery or another third-party utility for this