Reading JSON objects from javascript file using JINT - javascript

I've been supplied with a javascript file containing two JSON objects such as this.
var languages = {"Languages":["English","Cymraeg","Deutsch"]};
var labels = [{"$JOB":["Job","Orchwyl","Auftrag",]},{"$JOB_NO":["Job Number","Rhiforchwyl","Auftragsnummer"]}];
I need to serialise the two JSON objects into something I can manipulate within .NET. I'm using JINT to get the two values from the file like this.
Engine js = new Engine();
js.Execute(fileContents);
languages = js.GetValue("languages");
labels = js.GetValue("labels");
But I can't do anything with the two values now. I can't parse the JSON, the values just come out as a strange object array where I can't actually determine the values.
Any suggestions on how I can get access to the JSON objects?

There is no JSON here.
This is javascript code, that creates javascript objects when it's evaluated.
Now, you can convert that javascript object into a JSON string.
The simplest way I found, was to have JINT do it for me, but I'm no expert in Jint, there might be better ways.
// Run javascript, inside the interpreter, to create JSON strings
js.Execute("languages = JSON.stringify(languages)");
js.Execute("labels = JSON.stringify(labels)");
// Extract the strings from the JS environment, into your c# code as strings
// Now, you can deserialize them as normal JSON
var languagesJsonString = js.GetValue("languages").AsString();
var labelsJsonString = js.GetValue("labels").AsString();

Related

How do you access multi-dimensional arrays of objects in JavaScript?

I need to access JavaScript objects stored in a multi-dimensional array. The data is being exported by a WordPress plug-in. Note, I cannot change the code to use a single array.
There are two arrays named "employees". Is this array format compatible with JavaScript? The JSON export was intended for PHP processing.
(Note, The code below is a simplified model to illustrate the issue).
var data = '{"employees":[{"firstName":"John0"}, {"firstName":"Anna0"},{"firstName":"Peter0"}],"employees":[{"firstName":"John1"}, {"firstName":"Anna1"},{"firstName":"Peter1"}]};';
var json = JSON.parse(data);
document.querySelector('#test').innerHTML = json.employees[2].firstName;
Here it is on JSFiddle:
https://jsfiddle.net/2524fhf4/11/
How for example, would one access the value "Peter0" in the first array? In a single array, it would be accessed like this:
var result = json.employees[2].firstName;
It appears to me that in this format it is only possible to access the last array.
It appears to me that in this format it is only possible to access the
last array.
Because when your object literal has two (or more) keys of the same name, last one will override the rest of them.
Check this demo
var data = '{"employees":[{"firstName":"John0"}, {"firstName":"Anna0"},{"firstName":"Peter0"}],"employees":[{"firstName":"John1"}, {"firstName":"Anna1"},{"firstName":"Peter1"}]}';
console.log(JSON.parse(data)); //it will only display first one
In the above example, you can see that there is only one key of the data

How to convert a JSON string to a JSON string with a different structure

I am building an application where data is retrieved from a third party system as a JSON string. I need to convert this JSON string to another JSON string with a different structure such that it can be used with pre-existing functions defined in a internal Javascript library.
Ideally I want to be able to perform this conversion on the client machine using Javascript.
I have looked at JSONT as a means of achieving this but that project does not appear to be actively maintained:
http://goessner.net/articles/jsont/
Is there a de facto way of achieving this? Or do I have to roll my own mapping code?
You shouldn't be passing JSON into an internal JavaScript library. You should parse the JSON into a JS object, then iterate over it, transforming it into the new format
Example
var json = '[{"a": 1:, "b": 2}, {"a": 4:, "b": 5}]';
var jsObj = JSON.parse(json);
// Transform property a into aa and property b into bb
var transformed = jsObj.map(function(obj){
return {
aa: obj.a,
bb: obj.b
}
});
// transformed = [{aa:1, bb:2},{aa:4, bb:5}]
If you really want JSON you'd just call JSON.stringify(transformed)
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/map
Here's another answer with an even more complicated transformation How to make a jquery Datatable array out of standard json?
From what I can tell from the home page, the JSONT project is about transforming JSON into entirely different formats anyway (i.e. JSON => HTML).
It's going to be a lot simpler to write your own mapping code, possibly just as a from_json() method on the object you're creating (so YourSpecialObject.from_json(input); returns an instance of that object generated from the JSON data).
From your question, I'm not sure if this fits your use case, but hopefully someone else will have a better answer soon.
Another option is using XSLT. As there are SAX readers and writers for JSON, you can write happily use XSLT with JSON. There's no horrific JSON to XML and back conversion needs to go on. See: http://www.gerixsoft.com/blog/json/xslt4json
I can definitely see the irony in using a XML based language to tranform JSON - but it seems like a good option.
Otherwise you're probably best of writing your own mapping code.

Saving javascript objects as strings

This is for a gaming application.
In my game I want to save special effects on a player in a single field of my database. I know I could just put a refrence Id and do another table and I haven't taken that option off the table.
Edit: (added information) This is for my server in node not the browser.
The way I was thinking about storing the data is as a javascript object as follows:
effects={
shieldSpell:0,
breatheWater:0,
featherFall:0,
nightVision:0,
poisonResistance:0,
stunResistance:0,
deathResistance:0,
fearResistance:0,
blindResistance:0,
lightningResistance:0,
fireResistance:0,
iceResistance:0,
windResistance:0}
It seems easy to store it as a string and use it using effects=eval(effectsString)
Is there an easy way to make it a string or do I have to do it like:
effectsString=..."nightVision:"+effects.nightVision.toString+",poisonResistance:"+...
Serialize like that:
JSON.stringify(effects);
Deserialize like that:
JSON.parse(effects);
Use JSON.stringify
That converts a JS object into JSON. You can then easily deserialize it with JSON.parse. Do not use the eval method since that is inviting cross-site scripting
//Make a JSON string out of a JS object
var serializedEffects = JSON.stringify(effects);
//Make a JS object from a JSON string
var deserialized = JSON.parse(serializedEffects);
JSON parse and stringify is what I use for this type of storatge
var storeValue = JSON.stringify(effects); //stringify your value for storage
// "{"shieldSpell":0,"breatheWater":0,"featherFall":0,"nightVision":0,"poisonResistance":0,"stunResistance":0,"deathResistance":0,"fearResistance":0,"blindResistance":0,"lightningResistance":0,"fireResistance":0,"iceResistance":0,"windResistance":0}"
var effects = JSON.parse(storeValue); //parse back from your string
Here was what I've come up with so far just wonering what the downside of this solution is.
effectsString="effects={"
for (i in effects){
effectsString=effectsString+i+":"+effects[i]+","
}
effectsString=effectsString.slice(0,effectsString.length-1);
effectsString=effectsString+"}"
Then to make the object just
eval(effectsString)

JavaScript associativea array - passing a string as array key: value pairs

I know that I can create an associative array like this:
var MyAssocArray = {'sky':'blue', 'grass':'green'};
And I am very fond of using this method.
What I would like to do and am having trouble with is this:
I have strings saved like this:
var MyString = "'sky':'blue', 'grass':'green'";
And I want to be able to do this now:
var MyAssocArray = {MyString};
When I try that - I get this error:
invalid object initializer
What am I doing wrong?
How can I achieve this?
I found a different solution using PHP and JavaScript. The associative array string is echoed in the JavaScript code:
var Multidimensional_Arr[Multidimensional_Array_Key_Name] = {<?php echo $String_Pulled_From_Database; ?>}; // i.e. 'sky':'blue', 'grass':'green'
// The same can be done for a one-dimensional array
var My_Single_Dime_Arr = {<?php echo $String_Pulled_From_Database; ?>}; // i.e. 'sky':'blue', 'grass':'green'
Use JSON -- it's serialized JavaScript Object Notation and is pretty close to what you're doing.
You'd need to do
var MyAssocArray = JSON.parse(MyString);
Also, JSON uses double quotes, not single quotes; if you use simple objects, you can probably write code to just replace ' with "" in your strings, but it's tricky if the strings contain double-quotes.
If you are using a browser that doesn't implement JSON.parse(), you can either use the implementation on the JSON website (see links at bottom of this page) or if you're using jQuery, there's jQuery.parseJSON().
Warning: Your solution has a security risk, unless you are sure the data in the database has been sanitized:
var My_Single_Dime_Arr = {<?php echo $String_Pulled_From_Database; ?>}
This is equivalent to a call to eval(); if your database string has any malicious code it can do bad things. This is one reason why JSON was invented -- it's easy to ensure that its contents are valid (and hence safe) before evaluated.
Your overall architecture, as you have presented it to us, is [data in database] -> server-side PHP -> client-side JavaScript. This is a classic example of serialized data. I realize you may have constraints to keep your system running without interruption, but a strict serialization format would make your system more secure.
If you are sure the data is safe, then you could do:
var MyAssocArray = eval('{' + MyString + '}');
You can't do that.
To achieve what you want, use the split() function to split your string into comma-separated tokens first. Then each token should further be split by the ':' character.
Then push the two tokens obtained by the last split as the key and the value of your associative array.

What can I do with JSON?

I want to, in brief, find out about what I can do with JSON; whether it is an alternative for JavaScript or what?
JSON is short for JavaScript Object Notation. It is a data format used for passing around data, modeled after the Javascript syntax for object/list literals. It is not a programming language, but rather a data markup language.
It's just a data format that converts data structures such as objects & arrays into a string representation. It uses the same format as javascript and is very easy to work with in ajax based applications because of this.
What can you do with json? anything that any other major data format can do. It's just data. What you can do with it is up to you.
JSON (an acronym for JavaScript Object Notation) is a lightweight text-based open standard designed for human-readable data interchange. It is derived from the JavaScript programming language for representing simple data structures and associative arrays, called objects
JSON is built on two structures:
A collection of name/value pairs.
An ordered list of values.
For more on JSON
In a brief JSON is JavaScript Object Notation. Which for example instead of doing:
var obj = new Object( );
obj.arr = new Array( );
obj.name = new String ( "Jhon Doe");
You can do:
var obj = { name: "Jhon Doe", arr: [1,2,3,4]};
So once browser will receive or meet some peace of JSON it would be able to compile it into Javascript object, so you will be able to use itt later in the code and reference to it.

Categories

Resources