javascript multiline dict declaration - javascript

I'm having an issue. I want to have a static dict
var myDict={"aaa":true,"aab":false,"aac":false,"aad":true, [...] };
There are a lot of entries, and I want to have an easy access to all of them in case I need to change their value. Because of this, I don't like the single-line declaration.
As an alternative, I did manage to do the following, since multi-line text is allowed in Javascript:
var dict = {};
var loadDict = function() {
text = "aaa,true\n\
aab,false\n\
aac,false\n\
aad,true\n\[...]";
var words = text.split( "\n" );
for ( var i = 0; i < words.length; i++ ) {
var pair = words[i].split(",");
dict[ pair[0].trim() ] = pair[1].trim();
}
}
Is there a better/more elegant way of having a multi-line declaration of a dict?
note: Creating multiline strings in JavaScript is a solution only for strings. it doesn't work with a dict.
edit: I was adding a '\' at the end of each line. That was the issue. thanks.

var myDict = {
"aaa": true,
"aab": false,
"aac": false,
"aad": true,
[...]
};
I hope this is what you meant, because it's basic Javascript syntax.
Also, if for some reasons you want to "store" simple objects (made of strings, numbers, booleans, arrays or objects of the above entities) into strings, you can consider JSON:
var myDictJSON = '{\
"aaa": true,\
"aab": false,\
"aac": false,\
"aad": true,\
[...]
}';
var myDict = JSON.parse(myDictJSON);
Support for JSON is native for all the major browsers, including IE since version 8. For the others, there's this common library json2.js that does the trick.
You can also convert your simple objects into string using JSON.stringify.

that's easy-
var myDict={
"aaa":true,
"aab":false,
"aac":false,
"aad":true
};
please remember, don't place the curly bracket in the next line.
i like responses. Please respond

This (a complex data structure containing both "string" and "booleans"):
var myDict={"aaa":true,"aab":false,"aac":false,"aad":true, [...] };
Can be expressed like this:
var myDict={
"aaa":true,
"aab":false,
"aac":false,
"aad":true,
[...]
};
Similarly, this:
var myBigHairyString = "Supercalifragilsticexpialidocious";
Can be expressed like this:
var myBigHairyString =
"Super" +
"califragilstic" +
"expialidocious";

Related

Tau-Prolog Interpreter shows different behaviour than SWI-Prolog

I'm currently trying to implement some basic Prolog queries in Tau-Prolog. Although I have working queries in SWI-Prolog, I can't implement them to work in Tau-Prolog.
I would like to return the name of all Robots that are in the database and have the Interface "B".
Is there something important I am missing here? I think that sub_string/5 might be the reason why it's not working. It also won't work when I paste the Code into the trial interpreter on http://tau-prolog.org/
Does anyone know a way to fix this query so it could work in Tau-Prolog? Thanks in advance!
<script>
var session = pl.create(1000)
var database = `
robot('Roboter1','A', 1, 550).
robot('Roboter2','C', 2, 340).
robot('Roboter3','B', 2, 430).
robot('Roboter4','A', 2, 200).
robot('Roboter5','B', 3, 260).
`
function start_query_RwB(){
query_RwB();
}
function query_RwB(){
var queryRwB = "queryRwB :-write('Interface B has: '),robot(Name, Interface,_,_),sub_string(Interface,_,_,_,'B'),write(Name),nl, fail."
var code_pl = database.concat(queryRwB);
var parsed = session.consult(code_pl)
var query = session.query('queryRwB.')
function inform(msg) {
show_result4.innerHTML += msg
}
session.current_output.stream.put = inform;
var callback = function(answer) {
}
session.answer(callback);
}
</script>
Use sub_atom/5 instead of sub_string/5 in the definition of the queryRwB variable as you use atoms, not strings, in the definition of the predicate robot/4:
var queryRwB = "queryRwB :-write('Interface B has: '),robot(Name, Interface,_,_), sub_atom(Interface,_,_,_,'B'),write(Name),nl, fail."
Note that sub_atom/5 is a standard predicate (that's implemented by Tau Prolog) while sub_string/5 is a proprietary predicate only found in some Prolog systems like ECLiPSe and SWI-Prolog.

JavaScript selecting Object Arraylike?

The Problem is the following:
I have a JSON file that has objects with the following name: "item0": { ... }, "item1": { ... }, "item2": { ... }. But I can't access them when going through an if method.
What I've done so far:
$.getJSON('/assets/storage/items.json', function(data) {
jsonStringify = JSON.stringify(data);
jsonFile = JSON.parse(jsonStringify);
addItems();
});
var addItems = function() {
/* var declarations */
for (var i = 0; i < Object.keys(jsonFile).length; i++) {
path = 'jsonFile.item' + i;
name = path.name;
console.log(path.name);
console.log(path.type);
}
}
If I console.log path.name it returns undefined. But if I enter jsonFile.item0.name it returns the value. So how can I use the string path so that it's treated like an object, or is there an other way on how to name the json items.
As others stated 'jsonFile.item' + i is not retrieving anything from jsonFile: it is just a string.
Other issues:
It makes no sense to first stringify the data and then parse it again. That is moving back and forth to end up where you already were: data is the object you want to work with
Don't name your data jsonFile. It is an object, not JSON. JSON is text. But because of the above remark, you don't need this variable
Declare your variables with var, let or const, and avoid global variables.
Use the promise-like syntax ($.getJSON( ).then)
Iterate object properties without assuming they are called item0, item1,...
Suggested code:
$.getJSON('/assets/storage/items.json').then(function(data) {
for (const path in data) {
console.log(data[path].name, data[path].type);
}
});
What you want is to use object notation using a dynamic string value as a key instead of an object key. So, instead of using something like object.dynamicName you either have use object[dynamicName].
So in your example it would be like this.
path = 'item' + i;
jsonFile[path].name
I'm afraid you cannot expect a string to behave like an object.
What you can do is this:
path = `item${i}`
name = jsonFile[path].name

Import text json for node js template literals

For my node js projects i typically have a text.json file and require it, instead of having static text within my code. something like below
JSON file
{
"greet":"Hello world"
}
var text = require('./text.json');
var greet = text.greet
I am having a little trouble in figuring out how this would work with template literals ?
I know this is an old issue but I just came up with a need for the same thing and.. yeah there are node modules that help do this but, this isn't that complex so I just made my own solution
function injectVariables( replacements, input ) {
const entries = Object.entries(replacements)
const result = entries.reduce( (output, entry) => {
const [key, value] = entry
const regex = new RegExp( `\\$\{${key}\}`, 'g')
return output.replace( regex, value )
}, input )
return result
}
const template = 'Hello my name is ${name} and I like ${language}'
const inputs = { name: 'David', language: 'JavaScript' }
const replaced = injectVariables(inputs, template)
console.log(replaced)
So, in this, it takes an input string and an object where the keys are the variable names in the string and the values are, you guessed it, the values.
It creates an array the values using Object.entries and then runs reduce across the entries to keep an updated version of the string as you go. On each iteration it makes a regex to match the variable expression and replaces that value with the one passed it.
This in particular won't look through nested objects (I didn't need that) but if for example your string had ${name.last} in it, since object keys can be strings, your input variable could be inputs = { 'name.last': 'Smith' } and it should work.
Hopefully this helps someone else.
I often use a very tiny templating helper library (tim - https://github.com/premasagar/tim) and it can be used to accomplish this:
//in my json file
var strings = {
'Hello': 'Hello {{name}}!',
'Goodbye': 'Goodbye {{name}}!'
};
//in my app
var tim = require('tim'); //templating library
var strings = require('./strings.json');
//replace
console.log(tim(strings.Hello,{name:'Fred'}));
Relevant JSFiddle:
https://jsfiddle.net/rtresjqv/
Alternatively, you could turn your strings into functions and then pass in the arguments:
//in my json file
var strings = {
'Hello': function() { return `Hello ${arguments[0]}!`; },
'Goodbye': function() { return `Goodbye {$arguments[0]}!`; }
};
//in my app
var strings = require('./strings.json');
//replace
console.log(strings.Hello('Fred'));
Fiddle:
https://jsfiddle.net/t6ta0576/

Java: Get JavaScript Array Elements from page

I am at a point where I can pull a single javascript declaration such as:
var cars = ["Saab", "Volvo", "BMW"];
parsed from a page.
I would like to be able to get all the elements of the array ("Saab", "Volvo", "BMW") from this declaration.
Should I be using some javascript engine for this, or what else would be the best way to get javascript variable values from my Java code.
I would hate to reinvent the wheel if something is already out there that is able to do this, so I am just looking for advice on something I can use to do this function.
I assume you found a way to transport that javascript object/array into your Java domain as a String or Stream. What you want now is a JSON parser.
One way is to use json.org or other libraries. Further information about json parsing can be found in this thread:
How to parse JSON in Java
The [org.json][1] library is easy to use. Example code below:
import org.json.*;
JSONObject obj = new JSONObject(" .... ");
String pageName = obj.getJSONObject("pageInfo").getString("pageName");
JSONArray arr = obj.getJSONArray("posts");
for (int i = 0; i < arr.length(); i++)
{
String post_id = arr.getJSONObject(i).getString("post_id");
......
} You may find extra examples from: [Parse JSON in Java][2]
Downloadable jar: http://mvnrepository.com/artifact/org.json/json
[1]: http://www.json.org/java/index.html
[2]: http://theoryapp.com/parse-json-in-java/
You might also want to look into jsonb (https://jcp.org/en/jsr/detail?id=353) that was introduced with Java 7. You can bind an object model and transform JSON objects into java objects and vice versa.
you can iterate through all the values in 'window'
for ( var key in window )
{
if ( typeof window]key] == 'object' && window]key].length > 0 )
{
//this is the array you are looking for
}
}
You can get access to javascript object from java by using httpunit
Method 1: JSON parser, as Alex's answer.
Method 2: Javascript parser for Java
Method 3: Regular Expression (A weird way I figured out!)
First pattern is var\s+([a-zA-Z0-9]+)\s+=\s+\[(.*)\]\s*;*
var + one or more space(s) + variable name($1) + one or more space(s) + equals sign + one or more space(s) + array content($2) + ......
Second pattern is "(.*?)", get the string between two quotation marks.
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class JSParser {
public String arrayName;
private String tempValues;
public ArrayList<String> values = new ArrayList<String>();
public boolean parseJSArray(String arrayStr){
String p1 = "var\\s+([a-zA-Z0-9]+)\\s+=\\s+\\[(.*)\\]\\s*;*";
Pattern pattern1 = Pattern.compile(p1);
Matcher matcher = pattern1.matcher(arrayStr);
if(matcher.find()){
arrayName = matcher.group(1);
tempValues = matcher.group(2);
Pattern getVal = Pattern.compile("\"(.*?)\"");
Matcher valMatcher = getVal.matcher(tempValues);
while (valMatcher.find()) { // find next match
String value = valMatcher.group(1);
values.add(value);
}
return true;
}else{
return false;
}
}
}
With JDK 8 the code bellow works :
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
String js = "var carsfromjs = [\"Saab\", \"Volvo\", \"BMW\"]";
engine.eval(js);
String[] cars = (String[])engine.eval("Java.to(carsfromjs, \"java.lang.String[]\")");
for(int i=0; i<cars.length; i++){
System.out.println(cars[i]);
}
You can find many ways to access Javascript code throught "nashorn" :
http://winterbe.com/posts/2014/04/05/java8-nashorn-tutorial/
http://www.oracle.com/technetwork/articles/java/jf14-nashorn-2126515.html
http://docs.oracle.com/javase/8/docs/technotes/guides/scripting/nashorn/

concatenate string from JSON

I would like to pull the longitudes and latitudes from an ESRI geometry and concatenate them in to a long string (to be used in an API call).
I am struggling with how to accomplish this
The ESRI documentation for geometry (geometry specs) shows the structure of the object but my API call needs the latitude/longitudes in the following format:
long1,lat1,long2,lat2,long3,lat3 ... long1, lat1
All I have to do is process the long/lats a little bit. Making a very simple example from the ESRI documentation
MyTest = {
"rings": [
[
[-97.06138, 32.837],
[-97.06133, 32.836],
[-97.06124, 32.834],
[-97.06127, 32.832],
[-97.06138, 32.837]
]
],
"spatialReference": {
"wkid": 4326
}
};
alert(JSON.stringify(MyTest.rings[0]));
Will give me the rings (the Longitudes/Latitudes) (notice the first long/lat is repeated as the last long/lat)
I cannot seem to figure out how to strip off the [ and ] to create a string with just the longitudes and latitudes. For instance:
myTest2 = MyTest.rings[0]; // get the longitudes and latitudes
myTest3 = JSON.stringify(myTest2);
myTest4 = myTest3.replace("[","");
alert(JSON.stringify(myTest2));
alert(JSON.stringify(myTest4));
The replace will strip off one of the brackets but I cannot get it to do a global replace like this post stack javascript replace because my programming environment is all within ColdFusion and I need the quotes around the pattern.
Can someone point out my error please ? Thanks !
You may try this (Example) using join():
MyTest = { "rings": [...] };
var str = MyTest.rings.join();
Result (in str) would be:
-97.06138,32.837,-97.06133,32.836,-97.06124,32.834,-97.06127,32.832,-97.06138,32.837
You have an object, use it - don't play with the stringified version.
var coords = MyTest.rings[0];
var list = [];
for ( var i = 0; i < coords.length; ++i )
{
list.push(coords[i][0]);
list.push(coords[i][1]);
}
var str = list.join(',');
// str is now "-97.06138,32.837,-97.06133...(etc.)"
DEMO: http://jsfiddle.net/gunderjt/B5wsK/2/
MyTest.rings[0].join()
and join with no parameters delineates with commas automatically
These are absolute basics, but you don't need to replace anything. [] is just an JavaScript array and not a string.
MyTest.rings.map(function (r) { return r.join(','); }).join(',');
// "-97.06138,32.837,-97.06133,32.836,-97.06124,32.834,-97.06127,32.832,-97.06138,32.837"
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join

Categories