I'm using the very simple Refify npm module to handle circular structure JSON. It stringifies a circular structure JSON object in Node.js to then send to the client. My Angular frontend receives the stringified JSON and needs to call the parse method of refify to convert it back to a usable object.
How do I include the refify node module in my Angular frontend so I can reference refify?
Backend usage looks like so:
var refify = require("refify");
app.get("/api/entries, function(req, res){
var circularJSON = //a circular JSON object
res.send(refify.stringify(circularJSON));
});
The frontend reference would look like this:
$http.get("/api/entries").success(function(data){
$scope.entries = refify.parse(data);
});
You can either use browserify as a build step, or you could use wzrd.in CDN, which is a CDN for npm modules.
browserify as a build step
Use node-style require() to organize your browser code and load modules installed by npm. Browserify will recursively analyze all the require() calls in your app in order to build a bundle you can serve up to the browser in a single <script> tag. For more information, and examples, click here.
wzrd.in CDN
<script src="https://wzrd.in/standalone/refify#latest"></script>
<script>
window.refify // You can use refify now!
</script>
You can go to https://wzrd.in/standalone/refify#latest, copy the code, and paste it into your own file if you want. See jsfiddle here.
Here is the forked version of Refify you can use in node.js as well as browsers.
Forked Refify
You can simply download the index.js and include it in your AngularJS application. and use it.
see the below code, I have added the whole forked index.js file in snippet and example at the end.
(function(obj) {
if (typeof exports === 'undefined') {
obj.refify = refify;
} else {
module.exports = refify;
}
function refify(obj) {
var objs = [];
var paths = []
var keyStack = [];
var objStack = [];
return walk(obj);
function walk(it) {
if (typeof it !== 'object') {
return it;
}
objs.push(it);
paths.push(keyStack.slice())
objStack.push(it)
var copy = initCopy(it);
for (var k in it) {
keyStack.push(k);
var v = it[k];
var i = objs.indexOf(v);
if (i == -1) {
copy[k] = walk(v)
} else {
var $ref = '#/' + paths[i].join('/');
copy[k] = {
$ref: $ref
};
}
keyStack.pop();
}
objStack.pop();
return copy;
}
}
refify.parse = function(it) {
if (typeof it !== 'object') it = JSON.parse(it);
var keyStack = [];
var copy = initCopy(it);
walk(it);
return copy;
function walk(obj) {
if (typeof obj !== 'object') {
set(copy, keyStack.slice(), obj);
return;
}
for (var k in obj) {
keyStack.push(k);
var current = obj[k];
var objPath = parseRef(current);
while (objPath) {
current = get(copy, objPath);
objPath = parseRef(current);
}
if (current === obj[k]) {
// We did *not* follow a reference
set(copy, keyStack.slice(), initCopy(current));
walk(current);
} else {
// We *did* follow a reference
set(copy, keyStack.slice(), current);
}
keyStack.pop();
}
}
}
refify.stringify = function(obj, replacer, spaces) {
return JSON.stringify(refify(obj), replacer, spaces)
}
function parseRef(value) {
if (typeof value !== 'object') return false;
if (!value.$ref) return false;
var path = value.$ref == '#/' ? [] : value.$ref.split('/').slice(1);
return path
}
function get(obj, path) {
if (!path.length) return obj;
if (typeof obj !== 'object') return;
var next = obj[path.shift()];
return get(next, path);
}
refify.set = set;
function set(obj, path, value) {
if (path.length === 0) throw new Error("Cannot replace root object");
var key = path.shift();
if (!path.length) {
obj[key] = value;
return;
}
switch (typeof obj[key]) {
case 'undefined':
obj[key] = isNaN(parseInt(key, 10)) ? {} : [];
break;
case 'object':
break;
default:
throw new Error("Tried to set property " + key + " of non-object " + obj[key]);
}
set(obj[key], path, value);
}
function initCopy(obj) {
if (typeof obj !== 'object') return obj;
return Array.isArray(obj) ? [] : {}
}
}(this));
// Example with forked version
var obj = {
inside: {
name: 'Stackoverflow',
id: '98776'
}
};
obj.inside.parent = obj;
var refifyObject= refify(obj);
document.getElementById("out").innerHTML = JSON.stringify(refifyObject);
<div id="out"></div>
if you want use module in browser, you can use Commonjs and AMD
for example :
requirejs.org
browserify
commonjs.org
systemjs
you can convert refify to module ( browserify ,requirejs,commonjs,...) and use.
Useful Links :
create module in RequireJS
writing modular js/
Related
This is not for web development. I am using ES3.
How do I get the information from the xml element proof using javascript in this scenario?
My way of looking for the proof element with xml[xmlVariable] doesn't work - it returns nothing. But when you enter xml.ait.pages.proof in the console (while the program is held by breakpoint at the return expression) it returns the "desired info" from the proof element correctly.
I've read up on dot/bracket notation thinking that would be the solution but nope.
What's the correct syntax here?
<root>
<ait>
<pages>
<proof>desired info</proof>
</pages>
</ait>
</root>
var xmlFile = "C:\Users\user\Desktop\info.xml"
var xmlElementPath = "ait.pages.proof"
var info = readXMLVar(xmlElementPath, xmlFile)
function readXMLVar(xmlVariable, xmlFilePath) {
var file = new File(xmlFilePath)
file.open("r")
var content = file.read()
file.close()
var xml = new XML(content)
return xml[xmlVariable]
}
For XML I would probably query using XPath. The code you're using, however, seems to create an object structure from the parsed XML, and you then want to ask for a part of that structure using a path to it, as it were.
You can use square bracket notation as you tried, but you have to do it one property/node-level at a time. JS doesn't parse the dot separated path you provided to walk into the nested structure.
As such, you need something that can break apart the path you want, and recursively walk down the structure node by node.
Here is a basic function that can walk an object structure:
var getNodeFromPath = function (data, path, separator) {
var node_name,
node,
ret;
if (!Array.isArray(path)) {
path = path.split(separator || '.');
}
node_name = path.shift();
node = data[node_name];
if (node === undefined) {
ret = null;
} else {
if (path.length) {
ret = getNodeFromPath(node, path);
} else {
ret = node;
}
}
return ret;
};
You could call it like so:
var proof_element = getNodeFromPath(yourParsedXmlData, 'ait.pages.proof');
Note that the function I gave you has minimal control in it. You'll probably want to add some checking to make it more resistant to arbitrary input data/path problems.
Applied fixes to JAAulde's answer and some slight modifications to fit into my function. Here is my code to get and set XML variables.
!(Object.prototype.toString.call(path) === '[object Array]') is used in place of !Array.isArray(path) because I'm forced to use ES3.
function readXMLFile(xmlFilePath) {
var file = new File(xmlFilePath)
file.open("r")
var content = file.read()
file.close()
return [file, new XML(content)]
}
function getXMLVar(xmlFilePath, nodePath, separator) {
var xml = readXMLFile(xmlFilePath)[1]
// navigate xml to return target node info
var getNodeFromPath = function(data, path, separator) {
var node_name,
node,
ret
if(!(Object.prototype.toString.call(path) === '[object Array]')) {
path = path.split(separator || '.')
}
node_name = path.shift()
node = data[node_name]
if(node === undefined) {
ret = null
} else {
if(path.length) {
ret = getNodeFromPath(node, path, separator)
} else {
ret = node
}
}
return ret
}
return getNodeFromPath(xml, nodePath, separator)
}
function setXMLVar(xmlFilePath, nodePath, separator, value) {
var read = readXMLFile(xmlFilePath)
var file = read[0]
var xml = read[1]
setNodeFromPath = function(data, path, separator, value) {
var node_name,
node
if(!(Object.prototype.toString.call(path) === '[object Array]')) {
path = path.split(separator || '.')
}
node_name = path.shift()
node = data[node_name]
if(path.length > 1) {
setNodeFromPath(node, path, separator, value)
} else {
node[path[0]] = value
}
}
setNodeFromPath(xml, nodePath, separator, value)
file.open("w")
file.write(xml)
file.close()
}
I've searched and searched but cannot find a better way to search through a JSON object and return a nested object that corresponds to a specific key.
I've found examples that work in javascript but when I try to use that code in Google Apps Script I find that some of the function/modules are not supported.
deeply The script below works where objRet is a global variable but I wondered if there was a better way to do it?
var objRet;
function blahblah() {
traverse(api_info, "EarningsRates");
// use this.objRet to process code
}
function traverse(json, keyData) {
var keyData = keyData;
var json = json;
if (Array.isArray(json)) {
json.forEach(traverse);
} else if (typeof json === 'object') {
Object.keys(json).forEach(function(key) {
if (key === keyData) {
this.retObj = json[key];
} else {
traverse(json[key], keyData);
}
});
}
}
I found this and would love to get it working but no luck with Google Apps Script
This function implements DFS: (depth first search)
function findDFS(objects, id) {
for (let o of objects || []) {
if (o.uuid == id) return o
const o_ = findDFS(o.children, id)
if (o_) return o_
}
}
And BFS:(breadth first search)
function findBFS(objects, id) {
const queue = [...objects]
while (queue.length) {
const o = queue.shift()
if (o.uuid == id) return o
queue.push(...(o.children || []))
}
}
I have a node/express server and I'm trying to get a function from a helper file to my app.js for use. Here is the function in the helper file:
CC.CURRENT.unpack = function(value)
{
var valuesArray = value.split("~");
var valuesArrayLenght = valuesArray.length;
var mask = valuesArray[valuesArrayLenght-1];
var maskInt = parseInt(mask,16);
var unpackedCurrent = {};
var currentField = 0;
for(var property in this.FIELDS)
{
if(this.FIELDS[property] === 0)
{
unpackedCurrent[property] = valuesArray[currentField];
currentField++;
}
else if(maskInt&this.FIELDS[property])
{
//i know this is a hack, for cccagg, future code please don't hate me:(, i did this to avoid
//subscribing to trades as well in order to show the last market
if(property === 'LASTMARKET'){
unpackedCurrent[property] = valuesArray[currentField];
}else{
unpackedCurrent[property] = parseFloat(valuesArray[currentField]);
}
currentField++;
}
}
return unpackedCurrent;
};
At the bottom of that helper file I did a module.export (The helper file is 400 lines long and I don't want to export every function in it):
module.exports = {
unpackMessage: function(value) {
CCC.CURRENT.unpack(value);
}
}
Then in my app.js I called
var helperUtil = require('./helpers/ccc-streamer-utilities.js');
and finally, I called that function in app.js and console.log it:
res = helperUtil.unpackMessage(message);
console.log(res);
The problem is that the console.log gives off an undefined every time, but in this example: https://github.com/cryptoqween/cryptoqween.github.io/tree/master/streamer/current (which is not node.js) it works perfectly. So I think I am importing wrong. All I want to do is use that utility function in my app.js
The unPackMessage(val) call doesn't return anything:
module.exports = {
unpackMessage: function(value) {
CCC.CURRENT.unpack(value);
}
}
you need to return CCC.CURRENT.UNPACK(value);
module.exports = {
unpackMessage: function(value) {
return CCC.CURRENT.unpack(value);
}
}
I have tried to copy the objects as text, but it show just [object object]. Before this I had tried with copy commend it was success but not now.Is that chrome issue?
What I tried?
Just Right click on the object and store as global variable from chrome console window, then next just used copy(temp6) command and tried to paste in notepad++.
It should ideally copy the object with the copy command that you wrote.
I just tried it and worked for me.
Something else that you can try to do is to stringify that object and then copy it.
Ex.
copy(JSON.stringify(temp6))
If the object already logged
Right-click on the object in console and click Store as a global
variable the output will be something like temp1
Copy and paste below code in chrome console and hit enter
(function(console){
console.save = function(data, filename){
if(!data) {
console.error('Console.save: No data')
return;
}
if(!filename) filename = 'console.json'
if(typeof data === "object"){
data = JSON.stringify(data, undefined, 4)
}
var blob = new Blob([data], {type: 'text/json'}),
e = document.createEvent('MouseEvents'),
a = document.createElement('a')
a.download = filename
a.href = window.URL.createObjectURL(blob)
a.dataset.downloadurl = ['text/json', a.download, a.href].join(':')
e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
a.dispatchEvent(e)
}
})(console)
Then you can use the function for downloading,
console.save(temp1);
-If it shows Uncaught TypeError: Converting circular structure to JSON
then you need decycle JSON object and paste below code in chrome browser console and hit enter
if (typeof JSON.decycle !== "function") {
JSON.decycle = function decycle(object, replacer) {
"use strict";
var objects = new WeakMap(); // object to path mappings
return (function derez(value, path) {
var old_path;
var nu;
if (replacer !== undefined) {
value = replacer(value);
}
if (
typeof value === "object" && value !== null &&
!(value instanceof Boolean) &&
!(value instanceof Date) &&
!(value instanceof Number) &&
!(value instanceof RegExp) &&
!(value instanceof String)
) {
old_path = objects.get(value);
if (old_path !== undefined) {
return {$ref: old_path};
}
objects.set(value, path);
if (Array.isArray(value)) {
nu = [];
value.forEach(function (element, i) {
nu[i] = derez(element, path + "[" + i + "]");
});
} else {
nu = {};
Object.keys(value).forEach(function (name) {
nu[name] = derez(
value[name],
path + "[" + JSON.stringify(name) + "]"
);
});
}
return nu;
}
return value;
}(object, "$"));
};
}
if (typeof JSON.retrocycle !== "function") {
JSON.retrocycle = function retrocycle($) {
"use strict";
var px = /^\$(?:\[(?:\d+|"(?:[^\\"\u0000-\u001f]|\\([\\"\/bfnrt]|u[0-9a-zA-Z]{4}))*")\])*$/;
(function rez(value) {
if (value && typeof value === "object") {
if (Array.isArray(value)) {
value.forEach(function (element, i) {
if (typeof element === "object" && element !== null) {
var path = element.$ref;
if (typeof path === "string" && px.test(path)) {
value[i] = eval(path);
} else {
rez(element);
}
}
});
} else {
Object.keys(value).forEach(function (name) {
var item = value[name];
if (typeof item === "object" && item !== null) {
var path = item.$ref;
if (typeof path === "string" && px.test(path)) {
value[name] = eval(path);
} else {
rez(item);
}
}
});
}
}
}($));
return $;
};
}
Then finally execute code for downloading.
console.save(JSON.decycle(temp1));
You can use command in console as follows:
Let say our object is:
var object = {x:"xyz"}
Now use below command in console -
copy(JSON.stringify(object))
object is now available to clipboard.You can now use Ctrl + v to use this object.
You should check thecount object to avoid circular reference, before using copy(JSON.stringify(count)), please see here
there can be many ways to do this. One way could be to do JSON.stringify(yourObject) and then copy the output.
You can also do this without having to write any code. At least with later version of chrome.
When you right click the object you get this context:
But if you left click the line to highlight it, the right click the console line you get this context menu:
The "Save as..." option will create text file (*.log) of everything "as is" currently on the console log. So if you want to see more of the object simply expand it as far as you need.
collapsed example:
let tmpArr = []; tmpArr.push([]); tmpArr[0].push({ some: 'test'}); tmpArr[0].push({ some: 'next'}); console.log(tmpArr);
VM242:1 [Array(2)]0: (2) [{…}, {…}]length: 1[[Prototype]]: Array(0)
undefined
null
null
expanded example:
let tmpArr = []; tmpArr.push([]); tmpArr[0].push({ some: 'test'}); tmpArr[0].push({ some: 'next'}); console.log(tmpArr);
VM242:1 [Array(2)]0: Array(2)0: some: "test"[[Prototype]]: Object1: some: "next"[[Prototype]]: Objectlength: 2[[Prototype]]: Array(0)length: 1[[Prototype]]: Array(0)
undefined
null
null
I am using node.js and as a side project i am creating a module that reads a .json file ,parse it then create directory structure based on object properties & object values.
Object properties(keys) would be the path to itself/to files & object values would be the list of files for that path
i have tried to recurse downwards through the object but i dont know how i extract the path from the inner-most object of each object
Also object would be dynamic as would be created by the user.
var path = 'c:/templates/<angular-app>';
var template = {
//outline of 'angular-app'
src:{
jade:['main.jade'],
scripts:{
modules:{
render:['index.js'],
winodws:['index.js'],
header:['header.js' ,'controller.js'],
SCSS:['index.scss' ,'setup.scss'],
}
}
},
compiled:['angular.js','angular-material.js' ,'fallback.js'],
built:{
frontEnd:[],//if the array is empty then create the path anyways
backEnd:[],
assets:{
fontAwesome:['font-awesome.css'],
img:[],
svg:[]
}
}
}
//desired result...
let out = [
'c:/template name/src/jade/main.jade',
'c:/template name/src/scripts/index.js',
'c:/template name/src/scripts/modules/render/index.js',
'c:/template name/compiled/angular.js',
'c:/template name/compiled/angular-material.js',
'c:/template name/compiled/fallback.js',
'c:/template name/built/frontEnd/',
'c:/template name/built/backEnd/',
//...ect...
];
Here's an example on how you can write this recursively:
var path = 'c:/templates';
var template = {
//outline of 'angular-app'
src: {
jade: ['main.jade'],
scripts: {
modules: {
render: ['index.js'],
winodws: ['index.js'],
header: ['header.js', 'controller.js'],
SCSS: ['index.scss', 'setup.scss'],
}
}
},
compiled: ['angular.js', 'angular-material.js', 'fallback.js'],
built: {
frontEnd: [], //if the array is empty then create the path anyways
backEnd: [],
assets: {
fontAwesome: ['font-awesome.css'],
img: [],
svg: []
}
}
}
function recurse(item, path, result) {
//create default output if not passed-in
result = result || [];
//item is an object, iterate its properties
for (let key in item) {
let value = item[key];
let newPath = path + "/" + key;
if (typeof value === "string") {
//if the property is a string, just append to the result
result.push(newPath + "/" + value);
} else if (Array.isArray(value)) {
//if an array
if (value.length === 0) {
//just the directory name
result.push(newPath + "/");
} else {
//itearate all files
value.forEach(function(arrayItem) {
result.push(newPath + "/" + arrayItem);
});
}
} else {
//this is an object, recursively build results
recurse(value, newPath, result);
}
}
return result;
}
var output = recurse(template, path);
console.log(output);
My solution for this problem would be as follows;
function getPaths(o, root = "", result = []) {
var ok = Object.keys(o);
return ok.reduce((a,k) => { var p = root + k + "/";
typeof o[k] == "object" && o[k] !== null &&
Array.isArray(o[k]) ? o[k].length ? o[k].forEach(f => a.push(p+=f))
: a.push(p)
: getPaths(o[k],p,a);
return a;
},result);
}
var path = 'c:/templates/',
template = {
//outline of 'angular-app'
src:{
jade:['main.jade'],
scripts:{
modules:{
render:['index.js'],
winodws:['index.js'],
header:['header.js' ,'controller.js'],
SCSS:['index.scss' ,'setup.scss'],
}
}
},
compiled:['angular.js','angular-material.js' ,'fallback.js'],
built:{
frontEnd:[],//if the array is empty then create the path anyways
backEnd:[],
assets:{
fontAwesome:['font-awesome.css'],
img:[],
svg:[]
}
}
},
paths = getPaths(template,path);
console.log(paths);
It's just one simple function called getPaths Actually it has a pretty basic recursive run. If your object is well structured (do not include any properties other than objects and arrays and no null values) you may even drop the typeof o[k] == "object" && o[k] !== null && line too. Sorry for my unorthodox indenting style but this is how i find to deal with the code more easy when doing ternaries, logical shortcuts and array methods with ES6 arrow callbacks.