Add the X values in Json with respect to Image - javascript

In a Json, there are multiple image sources as "src" : "image.png", , "src" : "image2.png",
For image.png , right now i am fetching X value as "40" [3rd position in below image]
For image2.png , right now i am fetching X value as "100" [6th position in below image]
Requirement :
Instead of that, i need to add 1st (10) + 3rd (40) + 4th (50) positions values and fetch final X value for "src" : "image.png", as 100 [10+40+50] and
"src" : "image1.png" = 1st (10) + 6th (100) + 7th (105) positions & final value of X is 215....
Codepen : https://codepen.io/kidsdial/pen/zbKaEJ
let jsonData = {
"layers" : [
{
"x" : 10,
"layers" : [
{
"x" : 20,
"y" : 30,
"name" : "L2a"
},
{
"x" : 40,
"layers" : [
{
"x" : 50,
"src" : "image.png",
"y" : 60,
"name" : "L2b-1"
},
{
"x" : 70,
"y" : 80,
"name" : "L2b-2"
}
],
"y" : 90,
"name" : "user_image_1"
},
{
"x" : 100,
"layers" : [
{
"x" : 105,
"src" : "image2.png",
"y" : 110,
"name" : "L2C-1"
},
{
"x" : 120,
"y" : 130,
"name" : "L2C-2"
}
],
"y" : 140,
"name" : "L2"
}
],
"y" : 150,
"name" : "L1"
}
]
};
function getData(data) {
var dataObj = {};
let layer1 = data.layers;
let layer2 = layer1[0].layers;
for (i = 1; i < layer2.length; i++) {
var x = layer2[i].x;
var src = layer2[i].layers[0].src;
document.write("src :" + src);
document.write("<br>");
document.write("x:" + x);
document.write("<br>");
}
}
getData(jsonData);

Using a recursive function you can find all the src and its corresponding summed x values.
Below is a crude example. Refactor as you see fit.
let jsonData = {
"layers" : [
{
"x" : 10,
"layers" : [
{
"x" : 20,
"y" : 30,
"name" : "L2a"
},
{
"x" : 40,
"layers" : [
{
"x" : 50,
"src" : "image.png",
"y" : 60,
"name" : "L2b-1"
},
{
"x" : 70,
"y" : 80,
"name" : "L2b-2"
}
],
"y" : 90,
"name" : "user_image_1"
},
{
"x" : 100,
"layers" : [
{
"x" : 105,
"src" : "image2.png",
"y" : 110,
"name" : "L2C-1"
},
{
"x" : 120,
"y" : 130,
"name" : "L2C-2"
}
],
"y" : 140,
"name" : "L2"
}
],
"y" : 150,
"name" : "L1"
}
]
};
function getAllSrc(layers){
let arr = [];
layers.forEach(layer => {
if(layer.src){
arr.push({src: layer.src, x: layer.x});
}
else if(layer.layers){
let newArr = getAllSrc(layer.layers);
if(newArr.length > 0){
newArr.forEach(({src, x}) =>{
arr.push({src, x: (layer.x + x)});
});
}
}
});
return arr;
}
function getData(data) {
let arr = getAllSrc(data.layers);
for (let {src, x} of arr){
document.write("src :" + src);
document.write("<br>");
document.write("x:" + x);
document.write("<br>");
}
}
getData(jsonData);
Here is the CodePen for the same: https://codepen.io/anon/pen/Wmpvre
Hope this helps :)

You can do that using recursion. While going though nested obj you could parent x value each item in layers and check if the element in layers have src property add the previous x value to it.
let jsonData = {
"layers" : [
{
"x" : 10,
"layers" : [
{
"x" : 20,
"y" : 30,
"name" : "L2a"
},
{
"x" : 40,
"layers" : [
{
"x" : 50,
"src" : "image.png",
"y" : 60,
"name" : "L2b-1"
},
{
"x" : 70,
"y" : 80,
"name" : "L2b-2"
}
],
"y" : 90,
"name" : "user_image_1"
},
{
"x" : 100,
"layers" : [
{
"x" : 105,
"src" : "image2.png",
"y" : 110,
"name" : "L2C-1"
},
{
"x" : 120,
"y" : 130,
"name" : "L2C-2"
}
],
"y" : 140,
"name" : "L2"
}
],
"y" : 150,
"name" : "L1"
}
]
};
function changeData(obj,x=0){
if(obj.src) obj.x += x;
if(obj.layers){
for(const item of obj.layers){
changeData(item,x+obj.x || 0);
}
}
}
changeData(jsonData);
function showData(obj){
if(obj.src) document.body.innerHTML += `src:${obj.src}<br>
x:${obj.x}<br>`;
if(obj.layers){
for(let i of obj.layers) showData(i)
}
}
showData(jsonData);
console.log(jsonData);

Here is my solution with recursion and mutation. You can cloneDeep the array before if you don't want to mutate it directly.
// Code
function recursion(obj, currentX = 0) {
if(obj.src) obj.x = currentX
else if(obj.layers) {
obj.layers.forEach(subObj => recursion(subObj, (currentX + subObj.x)))
}
}
// Data
let jsonData = {
"layers" : [
{
"x" : 10,
"layers" : [
{
"x" : 20,
"y" : 30,
"name" : "L2a"
},
{
"x" : 40,
"layers" : [
{
"x" : 50,
"src" : "image.png",
"y" : 60,
"name" : "L2b-1"
},
{
"x" : 70,
"y" : 80,
"name" : "L2b-2"
}
],
"y" : 90,
"name" : "user_image_1"
},
{
"x" : 100,
"layers" : [
{
"x" : 105,
"src" : "image2.png",
"y" : 110,
"name" : "L2C-1"
},
{
"x" : 120,
"y" : 130,
"name" : "L2C-2"
}
],
"y" : 140,
"name" : "L2"
}
],
"y" : 150,
"name" : "L1"
}
]
};
// Use
recursion(jsonData)
console.log(jsonData)

let jsonData = {
"layers": [{
"x": 10,
"layers": [{
"x": 20,
"y": 30,
"name": "L2a"
},
{
"x": 40,
"layers": [{
"x": 50,
"src": "image.png",
"y": 60,
"name": "L2b-1"
},
{
"x": 70,
"y": 80,
"name": "L2b-2"
}
],
"y": 90,
"name": "user_image_1"
},
{
"x": 100,
"layers": [{
"x": 105,
"src": "image2.png",
"y": 110,
"name": "L2C-1"
},
{
"x": 120,
"y": 130,
"name": "L2C-2"
}
],
"y": 140,
"name": "L2"
}
],
"y": 150,
"name": "L1"
}]
};
function getData(data) {
var dataObj = {};
let layer1 = data.layers;
let layer2 = layer1[0].layers;
let y = layer1[0].x;
for (i = 1; i < layer2.length; i++) {
var x = y;
x += layer2[i].x;
x += layer2[i].layers[0].x;
var src = layer2[i].layers[0].src;
document.write("src :" + src);
document.write("<br>");
document.write("x:" + x);
document.write("<br>");
}
}
getData(jsonData);

Here is My Solution. Check this out
let jsonData = {
"layers" : [
{
"x" : 10, //
"layers" : [
{
"x" : 20,
"y" : 30,
"name" : "L2a"
},
{
"x" : 40, //
"layers" : [
{
"x" : 50, //
"src" : "image.png",
"y" : 60,
"name" : "L2b-1"
},
{
"x" : 70,
"y" : 80,
"name" : "L2b-2"
}
],
"y" : 90,
"name" : "user_image_1"
},
{
"x" : 100,
"layers" : [
{
"x" : 105,
"src" : "image2.png",
"y" : 110,
"name" : "L2C-1"
},
{
"x" : 120,
"y" : 130,
"name" : "L2C-2"
}
],
"y" : 140,
"name" : "L2"
}
],
"y" : 150,
"name" : "L1"
}
]
};
var dataObj = [];
var x, src;
function getData(data) {
let layer1 = data.layers;
for(var i = 0; i < layer1.length; i++){
if(x === 0){
x = layer1[i].x;
continue;
}
x = layer1[i].x;
if(typeof layer1[i].layers !== 'undefined')
createOutput(layer1[i].layers);
}
return dataObj;
}
function createOutput(dataArray){
if(typeof dataArray === 'undefined'){
dataObj.push({x: x, src: src});
x = 0;
getData(jsonData);
return;
}
dataArray.forEach(element => {
if(typeof element.layers !== 'undefined' || typeof element.src !== 'undefined'){
x += element.x;
src = element.src;
createOutput(element.layers);
}
})
}
console.log(JSON.stringify(getData(jsonData)));

Related

Get the Multiple images & its positions from Json

I am fetching image & its positions [left(x) & top (y)] from json with help of below code & displaying in html page.... if there is single image in json, than its working fine....
var mask1;
$(document).ready(function()
{
var maskedImageUrla = "";
var coordinates = {
x: 0,
y: 0
};
var width = 0;
var height = 0;
$.getJSON('2images.json', function(json)
{
for (let layer of json.layers)
{
width = layer.width;
height = layer.height;
if (layer.layers && layer.layers.length > 0)
{
for (let temp of layer.layers)
{
if (temp.src) maskedImageUrla = temp.src;
else if (temp.layers)
{
for (let tl of temp.layers)
if (tl.src)
{
maskedImageUrla = 'http://piccellsapp.com:1337/parse/files/PfAppId/' + tl.src;
coordinates.x = temp.x;
coordinates.y = temp.y;
}
}
}
}
}
$(".container").css('width', width + "px").css('height', height + "px").addClass('temp');
var mask1 = $(".container").mask({
maskImageUrl: maskedImageUrla, // get image
onMaskImageCreate: function(img) {
img.css({
"position": "fixed",
"left": coordinates.x + "px", // get x
"top": coordinates.y + "px" // get y
});
}
});
fileupa1.onchange = function() {
mask1.loadImage(URL.createObjectURL(fileupa1.files[0]));
};
});
}); // end of document ready
Requirement :
but if there are multiple images in json, than only one image is fetching, but how to fetch all images [src] & its positions [ x & y ]....
Codepen [ 2 images json ] : https://codepen.io/kidsdial/pen/RdwXpZ
Edit : Below is Code snippet :
var mask1;
$(document).ready(function()
{
var maskedImageUrla = "";
var coordinates = {
x: 0,
y: 0
};
var width = 0;
var height = 0;
var json = {
"name": "newyear collage",
"layers": [
{
"x": 0,
"height": 612,
"layers": [
{
"x": 0,
"y": 0
},
{
"x": 160,
"layers": [
{
"x": 0,
"src": "AX7HBOE.png",
"y": 0,
"name": "mask_image_1"
},
{
"name": "useradd_ellipse1"
}
],
"y": 291,
"name": "user_image_1"
},
{
"x": 25,
"layers": [
{
"x": 0,
"src": "o5P9tdZ.png",
"y": 0,
"name": "mask_image_2"
},
{
"name": "useradd_ellipse_2"
}
],
"y": 22,
"name": "user_image_2"
}
],
"y": 0,
"width": 612,
"name": "newyearcollage08"
}
]
};
for (let layer of json.layers)
{
width = layer.width;
height = layer.height;
if (layer.layers && layer.layers.length > 0)
{
for (let temp of layer.layers)
{
if (temp.src) maskedImageUrla = temp.src;
else if (temp.layers)
{
for (let tl of temp.layers)
if (tl.src)
{
maskedImageUrla = 'https://i.imgur.com/' + tl.src;
coordinates.x = temp.x;
coordinates.y = temp.y;
}
}
}
}
}
$(".container").css('width', width + "px").css('height', height + "px").addClass('temp');
var mask1 = $(".container").mask({
maskImageUrl: maskedImageUrla, // get image
onMaskImageCreate: function(img) {
img.css({
"position": "fixed",
"left": coordinates.x + "px", // get x
"top": coordinates.y + "px" // get y
});
}
});
fileupa1.onchange = function() {
mask1.loadImage(URL.createObjectURL(fileupa1.files[0]));
};
}); // end of document ready
// jq plugin for mask
(function($) {
var JQmasks = [];
$.fn.mask = function(options) {
// This is the easiest way to have default options.
var settings = $.extend({
// These are the defaults.
maskImageUrl: undefined,
imageUrl: undefined,
scale: 1,
id: new Date().getUTCMilliseconds().toString(),
x: 0, // image start position
y: 0, // image start position
onMaskImageCreate: function(div) {},
}, options);
var container = $(this);
let prevX = 0,
prevY = 0,
draggable = false,
img,
canvas,
context,
image,
timeout,
initImage = false,
startX = settings.x,
startY = settings.y,
div;
container.mousePosition = function(event) {
return {
x: event.pageX || event.offsetX,
y: event.pageY || event.offsetY
};
}
container.selected = function(ev) {
var pos = container.mousePosition(ev);
var item = $(".masked-img canvas").filter(function() {
var offset = $(this).offset()
var x = pos.x - offset.left;
var y = pos.y - offset.top;
var d = this.getContext('2d').getImageData(x, y, 1, 1).data;
return d[0] > 0
});
JQmasks.forEach(function(el) {
var id = item.length > 0 ? $(item).attr("id") : "";
if (el.id == id)
el.item.enable();
else el.item.disable();
});
};
container.enable = function() {
draggable = true;
$(canvas).attr("active", "true");
div.css({
"z-index": 2
});
}
container.disable = function() {
draggable = false;
$(canvas).attr("active", "false");
div.css({
"z-index": 1
});
}
container.onDragStart = function(evt) {
container.selected(evt);
prevX = evt.clientX;
prevY = evt.clientY;
};
container.getImagePosition = function() {
return {
x: settings.x,
y: settings.y,
scale: settings.scale
};
};
container.onDragOver = function(evt) {
if (draggable && $(canvas).attr("active") === "true") {
var x = settings.x + evt.clientX - prevX;
var y = settings.y + evt.clientY - prevY;
if (x == settings.x && y == settings.y)
return; // position has not changed
settings.x += evt.clientX - prevX;
settings.y += evt.clientY - prevY;
prevX = evt.clientX;
prevY = evt.clientY;
container.updateStyle();
}
};
container.updateStyle = function() {
clearTimeout(timeout);
timeout = setTimeout(function() {
context.clearRect(0, 0, canvas.width, canvas.height);
context.beginPath();
context.globalCompositeOperation = "source-over";
image = new Image();
image.setAttribute('crossOrigin', 'anonymous');
image.src = settings.maskImageUrl;
image.onload = function() {
canvas.width = image.width;
canvas.height = image.height;
context.drawImage(image, 0, 0, image.width, image.height);
div.css({
"width": image.width,
"height": image.height
});
};
img = new Image();
img.src = settings.imageUrl;
img.setAttribute('crossOrigin', 'anonymous');
img.onload = function() {
settings.x = settings.x == 0 && initImage ? (canvas.width - (img.width * settings.scale)) / 2 : settings.x;
settings.y = settings.y == 0 && initImage ? (canvas.height - (img.height * settings.scale)) / 2 : settings.y;
context.globalCompositeOperation = 'source-atop';
context.drawImage(img, settings.x, settings.y, img.width * settings.scale, img.height * settings.scale);
initImage = false;
};
}, 0);
};
// change the draggable image
container.loadImage = function(imageUrl) {
if (img)
img.remove();
// reset the code.
settings.y = startY;
settings.x = startX;
prevX = prevY = 0;
settings.imageUrl = imageUrl;
initImage = true;
container.updateStyle();
};
// change the masked Image
container.loadMaskImage = function(imageUrl, from) {
if (div)
div.remove();
canvas = document.createElement("canvas");
context = canvas.getContext('2d');
canvas.setAttribute("draggable", "true");
canvas.setAttribute("id", settings.id);
settings.maskImageUrl = imageUrl;
div = $("<div/>", {
"class": "masked-img"
}).append(canvas);
div.find("canvas").on('touchstart mousedown', function(event) {
if (event.handled === false) return;
event.handled = true;
container.onDragStart(event);
});
div.find("canvas").on('touchend mouseup', function(event) {
if (event.handled === false) return;
event.handled = true;
container.selected(event);
});
div.find("canvas").bind("dragover", container.onDragOver);
container.append(div);
if (settings.onMaskImageCreate)
settings.onMaskImageCreate(div);
container.loadImage(settings.imageUrl);
};
container.loadMaskImage(settings.maskImageUrl);
JQmasks.push({
item: container,
id: settings.id
})
return container;
};
}(jQuery));
.temp
{
border: 1px solid #DDDDDD;
display: flex;
background :silver;
}
.container canvas {
display: block;
}
.masked-img {
overflow: hidden;
margin-top: 50px;
position: relative;
}
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
image 1
<input id="fileupa1" type="file" >
<div class="container">
</div>
</head>
let jsonData2 = {
"path" : " newyear collage\/",
"info" : {
"author" : "",
"keywords" : "",
"file" : "newyear collage",
"date" : "sRGB",
"title" : "",
"description" : "Normal",
"generator" : "Export Kit v1.2.8"
},
"name" : "newyear collage",
"layers" : [
{
"x" : 0,
"height" : 612,
"layers" : [
{
"x" : 0,
"color" : "0xFFFFFF",
"height" : 612,
"y" : 0,
"width" : 612,
"shapeType" : "rectangle",
"type" : "shape",
"name" : "bg_rectangle"
},
{
"x" : 160,
"height" : 296,
"layers" : [
{
"x" : 0,
"height" : 296,
"src" : "6b8e734c46539dbc73f51e8f65d29fe3_frame0.png",
"y" : 0,
"width" : 429,
"type" : "image",
"name" : "mask_image_1"
},
{
"radius" : "26 \/ 27",
"color" : "0xACACAC",
"x" : 188,
"y" : 122,
"height" : 53,
"width" : 53,
"shapeType" : "ellipse",
"type" : "shape",
"name" : "useradd_ellipse1"
}
],
"y" : 291,
"width" : 429,
"type" : "group",
"name" : "user_image_1"
},
{
"x" : 25,
"height" : 324,
"layers" : [
{
"x" : 0,
"height" : 324,
"src" : "eb8e531ec340da14688a6343769286c0_frame1.png",
"y" : 0,
"width" : 471,
"type" : "image",
"name" : "mask_image_2"
},
{
"radius" : "26 \/ 27",
"color" : "0xACACAC",
"x" : 209,
"y" : 136,
"height" : 53,
"width" : 53,
"shapeType" : "ellipse",
"type" : "shape",
"name" : "useradd_ellipse_2"
}
],
"y" : 22,
"width" : 471,
"type" : "group",
"name" : "user_image_2"
}
],
"y" : 0,
"width" : 612,
"type" : "group",
"name" : "newyearcollage08"
}
]
};
let jsonData = {
"path": " UNEVENSHAPES\/",
"info": {
"author": "",
"keywords": "",
"file": "UNEVENSHAPES",
"date": "Uncalibrated",
"title": "",
"description": "Normal",
"generator": "Export Kit v1.2.8"
},
"name": "UNEVENSHAPES",
"layers": [{
"x": 0,
"height": 612,
"layers": [{
"x": 0,
"color": "0xFFFFFF",
"height": 612,
"y": 0,
"width": 612,
"shapeType": "rectangle",
"type": "shape",
"name": "rectangle1"
},
{
"x": 20,
"height": 377,
"layers": [{
"x": 0,
"height": 377,
"src": "d15ad70281961be451263b418a07798b_frame0.png",
"y": 0,
"width": 218,
"type": "image",
"name": "mask_pic1"
},
{
"radius": "27 \/ 27",
"color": "0xACACAC",
"x": 52,
"y": 257,
"height": 53,
"width": 53,
"shapeType": "ellipse",
"type": "shape",
"name": "useradd_ellipse1"
}
],
"y": 215,
"width": 218,
"type": "group",
"name": "user_pic1"
},
{
"x": 191,
"height": 120,
"layers": [{
"x": 0,
"height": 120,
"src": "2b5d28d0439bc3ce1d856e6c4e5607be_frame1.png",
"y": 0,
"width": 268,
"type": "image",
"name": "mask_pic2"
},
{
"radius": "26 \/ 27",
"color": "0xACACAC",
"x": 115,
"y": 43,
"height": 53,
"width": 53,
"shapeType": "ellipse",
"type": "shape",
"name": "useradd_ellipse2"
}
],
"y": 472,
"width": 268,
"type": "group",
"name": "user_pic2"
},
{
"x": 414,
"height": 302,
"layers": [{
"x": 0,
"height": 302,
"src": "52c93b6e0a0ffeeb670d0981f89f7fa5_frame2.png",
"y": 0,
"width": 178,
"type": "image",
"name": "mask_pic3"
},
{
"radius": "26 \/ 27",
"color": "0xACACAC",
"x": 69,
"y": 182,
"height": 53,
"width": 53,
"shapeType": "ellipse",
"type": "shape",
"name": "useradd_ellipse3"
}
],
"y": 290,
"width": 178,
"type": "group",
"name": "user_pic3"
},
{
"x": 374,
"height": 377,
"layers": [{
"x": 0,
"height": 377,
"src": "e92f354018aa8f7e6d279601a868a6b2_frame3.png",
"y": 0,
"width": 218,
"type": "image",
"name": "mask_pic4"
},
{
"radius": "26 \/ 27",
"color": "0xACACAC",
"x": 129,
"y": 60,
"height": 53,
"width": 53,
"shapeType": "ellipse",
"type": "shape",
"name": "useradd_ellipse4"
}
],
"y": 20,
"width": 218,
"type": "group",
"name": "user_pic4"
},
{
"x": 150,
"height": 120,
"layers": [{
"x": 0,
"height": 120,
"src": "010054750abb290d1bd7fcecfab60524_frame4.png",
"y": 0,
"width": 269,
"type": "image",
"name": "mask_pic5"
},
{
"radius": "27 \/ 27",
"color": "0xACACAC",
"x": 103,
"y": 15,
"height": 53,
"width": 53,
"shapeType": "ellipse",
"type": "shape",
"name": "useradd_ellipse5"
}
],
"y": 20,
"width": 269,
"type": "group",
"name": "user_pic5"
},
{
"x": 20,
"height": 302,
"layers": [{
"x": 0,
"height": 302,
"src": "e7a5874b58376883adbeafea7ce5e572_frame5.png",
"y": 0,
"width": 176,
"type": "image",
"name": "mask_pic6"
},
{
"radius": "26 \/ 27",
"color": "0xACACAC",
"x": 50,
"y": 68,
"height": 53,
"width": 53,
"shapeType": "ellipse",
"type": "shape",
"name": "useradd_ellipse6"
}
],
"y": 20,
"width": 176,
"type": "group",
"name": "user_pic6"
},
{
"x": 222,
"height": 335,
"layers": [{
"x": 0,
"height": 335,
"src": "591743efa89d8ee936a6d660d52e82b2_frame6.png",
"y": 0,
"width": 265,
"type": "image",
"name": "mask_pic7"
},
{
"radius": "26 \/ 27",
"color": "0xACACAC",
"x": 126,
"y": 114,
"height": 53,
"width": 53,
"shapeType": "ellipse",
"type": "shape",
"name": "useradd_ellipse7"
}
],
"y": 123,
"width": 265,
"type": "group",
"name": "user_pic7"
},
{
"x": 123,
"height": 334,
"layers": [{
"x": 0,
"height": 334,
"src": "22997a60cf61d7b59e92620b86ab86d6_frame7.png",
"y": 0,
"width": 264,
"type": "image",
"name": "mask_pic8"
},
{
"radius": "27 \/ 27",
"color": "0xACACAC",
"x": 73,
"y": 167,
"height": 53,
"width": 53,
"shapeType": "ellipse",
"type": "shape",
"name": "useradd_ellipse8"
}
],
"y": 155,
"width": 264,
"type": "group",
"name": "user_pic8"
}
],
"y": 0,
"width": 612,
"type": "group",
"name": "unevenshape04"
}]
};
function getData(data) {
var dataObj = {};
let layer1 = data.layers;
let layer2 = layer1[0].layers;
console.log('New Data');
for (i = 1; i < layer2.length; i++) {
var x = layer2[i].x;
var y = layer2[i].y;
var src = layer2[i].layers[0].src;
console.log(x,y,src);
}
}
getData(jsonData);
getData(jsonData2);
the json part is ok. But after that in
var mask1 = $(".container").mask({
maskImageUrl: maskedImageUrla, // get image
you create only one image, with the last value of maskedImageUrla.
What you can do is store your images in an array and iterate over them, as in :
$.getJSON('2images.json', function(json)
{
const images = [];
for (let layer of json.layers)
...
for (let tl of temp.layers)
if (tl.src) {
images.push({
maskedImageUrla = 'http://piccellsapp.com:1337/parse/files/PfAppId/' + tl.src,
coordinates.x = temp.x,
coordinates.y = temp.y
})
}
...
images.forEach(image => {
var mask1 = $(".container").mask({
maskImageUrl: image.maskedImageUrla, // get image
onMaskImageCreate: function(img) {
img.css({
"position": "fixed",
"left": image.coordinates.x + "px", // get x
"top": image.coordinates.y + "px" // get y
});
}
});
fileupa1.onchange = function() {
mask1.loadImage(URL.createObjectURL(fileupa1.files[0]));
};
});

Cannot access a field in JSON

I am trying to access an image in a JSON response however the field I need to access is an id value that is unique or rather is random. We are fetching this data from a server so we cannot hard code the id's.
The JSON is as follows:
{ "error" : { "occured" : "false" },
"errors" : [ ],
"executiontime" : 2500,
"metadata" : { },
"value" : [ { "activity_duration" : "1 hour, ½ day & full day packages",
"adult_rate_high_period_high_price" : 275,
"adult_rate_high_period_low_price" : 49,
"adult_rate_low_period_high_price" : "",
"adult_rate_low_period_low_price" : "",
"amenities" : [ ],
"assets" : { "logo" : { "436209" : { "asset_type" : "image",
"caption" : "",
"credit" : "",
"description" : "",
"exists" : "true",
"height" : 82,
"label" : "Copy of Monarch logo",
"latitude" : 0,
"longitude" : 0,
"market" : "$",
"o_id" : 3221685,
"type_o_id" : 2543991,
"unique_id" : 436209,
"url" : "http://c0481729.cdn2.cloudfiles.rackspacecloud.com/p-DD951E3E-C7AF-F22C-77E98D299833B38F-2544001.jpg",
"width" : 220
} },
We are trying to display the business logo for each amenity. To do this I need to access the url field in the above JSON. How do I access the url field under assest.
The Problem is to get the id of the Logo 436209.
var theid;
var l = obj.value[0].assets.logo
for (var p in l) {
if (l[p].hasOwnProperty('unique_id')) {
theid = l[p].unique_id;
break;
}
}
This is untestet. The idee is to use the in-operator to iterate over the properties of the logo-object and get the propterty that has the unique_id.
Correction:
obj.value[0].assets.logo["436209"].url = 'foo';
// or
var foo = obj.value[0].assets.logo["436209"].url;
This assumes that your object is well formed and continues with more parts of obj.value[0].
Specifically, if your object were completed, perhaps, like this:
var obj = {
"error": { "occured": "false" },
"errors": [],
"executiontime": 2500,
"metadata": {},
"value": [{
"activity_duration": "1 hour, ½ day & full day packages",
"adult_rate_high_period_high_price": 275,
"adult_rate_high_period_low_price": 49,
"adult_rate_low_period_high_price": "",
"adult_rate_low_period_low_price": "",
"amenities": [],
"assets": {
"logo": {
"436209": {
"asset_type": "image",
"caption": "",
"credit": "",
"description": "",
"exists": "true",
"height": 82,
"label": "Copy of Monarch logo",
"latitude": 0,
"longitude": 0,
"market": "$",
"o_id": 3221685,
"type_o_id": 2543991,
"unique_id": 436209,
"url": "http://c0481729.cdn2.cloudfiles.rackspacecloud.com/p-DD951E3E-C7AF-F22C-77E98D299833B38F-2544001.jpg",
"width": 220
}
}
}
}]
};

Formatting JSON document to specification needed for visualization

I'm attempting to create a Google Chart based on data in Elastic Search. The JSON document needs to be in the following format:
{
"cols": [
{"id":"","label":"Lane","type":"string"},
{"id":"","label":"Routes","type":"number"}
],
"rows": [
{"c":[{"v":"M01"},{"v":4657}]},
{"c":[{"v":"M02"},{"v":4419}]},
{"c":[{"v":"M03"},{"v":4611}]},
{"c":[{"v":"M04"},{"v":4326}]},
{"c":[{"v":"M05"},{"v":4337}]},
{"c":[{"v":"M06"},{"v":5363}]}
]
}
My query (via ajax command) returns the following data:
$ curl http://localhost:9200/wcs/routes/_search?pretty=true -d '{"query_all":{}}}'
{
"took" : 2,
"timed_out" : false,
"_shards" : {
"total" : 5,
"successful" : 5,
"failed" : 0
},
"hits" : {
"total" : 7,
"max_score" : 1.0,
"hits" : [ {
"_index" : "wcs",
"_type" : "routes",
"_id" : "4",
"_score" : 1.0, "_source" : {"lane":"M04","routes":"102"}
}, {
"_index" : "wcs",
"_type" : "routes",
"_id" : "5",
"_score" : 1.0, "_source" : {"lane":"M03","routes":"143"}
}, {
"_index" : "wcs",
"_type" : "routes",
"_id" : "1",
"_score" : 1.0, "_source" : {"lane":"M07","routes":"80"}
}, {
"_index" : "wcs",
"_type" : "routes",
"_id" : "6",
"_score" : 1.0, "_source" : {"lane":"M02","routes":"157"}
}, {
"_index" : "wcs",
"_type" : "routes",
"_id" : "2",
"_score" : 1.0, "_source" : {"lane":"M06","routes":"101"}
}, {
"_index" : "wcs",
"_type" : "routes",
"_id" : "7",
"_score" : 1.0, "_source" : {"lane":"M01","routes":"105"}
}, {
"_index" : "wcs",
"_type" : "routes",
"_id" : "3",
"_score" : 1.0, "_source" : {"lane":"M05","routes":"160"}
} ]
}
}
The HTML/JS that I'm attempting to run (and currently returns nothing) is as follows. Could someone provide some insight as to what I may be doing wrong? It would be greatly appreciated.
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
google.load('visualization', '1', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = $.ajax({
url: 'http://localhost:9200/wcs/routes/_search?pretty=true'
, type: 'POST'
, data :
JSON.stringify(
{
"query" : { "match_all" : {} }
})
, dataType : 'json'
async: false
});
var json = JSON.parse(jsonData);
var jdata = '{ "cols": [{"id":"", "label":"lane", "type": "string"},' + '{"id": "", "label": "routes", "type": "number"}],' + '"rows":[{"c": [{"v":' + json.hits[0].hits[0]._source.lane + '},{"v":' + json.hits[0].hits[0]._source.routes + '}]}]';
var data = new google.visualization.DataTable(jdata);
var chart = new google.visualization.PieChart(document.getElementById('piechart_div'));
chart.draw(data, {is3D: true, title: 'Multi Routes per Lane', width: 600, height: 440});
}
</script>
</head>
<body>
<input type="button" onclick = "drawChart()" value="test">
<div id="piechart_div"> </div>
</body>
</html>
add the success handler in the ajax call. Also as Felix King pointed out, google.visualization.DataTable expects an JavaScript Object - not a string
So move all this code
var jdata = '{ "cols": [{"id":"", "label":"lane", "type": "string"},' + '{"id": "", "label": "routes", "type": "number"}],' + '"rows":[{"c": [{"v":' + json.hits[0].hits[0]._source.lane + '},{"v":' + json.hits[0].hits[0]._source.routes + '}]}]';
var data = new google.visualization.DataTable(jdata);
var chart = new google.visualization.PieChart(document.getElementById('piechart_div'));
chart.draw(data, {is3D: true, title: 'Multi Routes per Lane', width: 600, height: 440});
into the success handler
$.ajax({
url: 'http://localhost:9200/wcs/routes/_search?pretty=true'
, type: 'POST'
, data :
JSON.stringify(
{
"query" : { "match_all" : {} }
})
, dataType : 'json'
, success : function (json){ // <-- json = javascript object since you set dataType to 'json'
// your object to pass to DataTable
var jdata = {
"cols": [{
"id": "",
"label": "lane",
"type": "string"
}, {
"id": "",
"label": "routes",
"type": "number"
}],
"rows": [{
"c": [{
"v": json.hits[0].hits[0]._source.lane
}, {
"v": json.hits[0].hits[0]._source.routes
}]
}]
};
var data = new google.visualization.DataTable(jdata);
var chart = new google.visualization.PieChart(document.getElementById('piechart_div'));
chart.draw(data, {is3D: true, title: 'Multi Routes per Lane', width: 600, height: 440});
}
});
Was able to do this with the following code (thanks dinjas):
var json;
$.ajax({
url: 'http://localhost:9200/wcs/routes/_search',
type: 'POST',
data :
JSON.stringify(
{
"query" : { "match_all" : {} }
}),
dataType : 'json',
async: false,
success: function(data){
json = data;
}
})
var jdata = {};
jdata.cols = [
{
"id": "",
"label": "Lane",
"type": "string"
},
{
"id": "",
"label": "Routes",
"type":"number"
}
];
jdata.rows = [
{
"c": [
{
"v": json.hits.hits[0]._source.lane
},
{
"v": json.hits.hits[0]._source.routes
}
]
}
];

data manipulation in javascript

i have an array of information containing folders like this:
[
{
"ACLID" : 0,
"ID" : 100,
"auditInfoVersion" : 3435973836,
"createBy" : 2,
"createDate" : "04/12/2012 17:38:46",
"isSubFolder" : 0,
"name" : "Piyush1",
"objectType" : 3,
-->"parentID" : 3,
"policyID" : 2,
"sDescription" : "",
"updateBy" : 2,
"updateDate" : "04/12/2012 17:38:46"
},
{
"ACLID" : 0,
"ID" : 102,
"auditInfoVersion" : 3435973836,
"createBy" : 2,
"createDate" : "05/10/2012 12:38:25",
"isSubFolder" : 0,
"name" : "New",
"objectType" : 3,
-->"parentID" : 3,
"policyID" : 2,
"sDescription" : "",
"updateBy" : 2,
"updateDate" : "05/10/2012 12:38:25"
},
{
"ACLID" : 0,
"ID" : 103,
"auditInfoVersion" : 3435973836,
"createBy" : 2,
"createDate" : "05/14/2012 18:00:22",
"isSubFolder" : 0,
"name" : "SegFolderWithDiffPolicy",
"objectType" : 3,
-->"parentID" : 3,
"policyID" : 39,
"sDescription" : "",
"updateBy" : 2,
"updateDate" : "05/14/2012 18:00:22"
},
{
"ACLID" : 0,
"ID" : 104,
"auditInfoVersion" : 3435973836,
"createBy" : 2,
"createDate" : "05/17/2012 14:13:56",
"isSubFolder" : 0,
"name" : "New1",
"objectType" : 3,
-->"parentID" : 100,
"policyID" : 2,
"sDescription" : "",
"updateBy" : 2,
"updateDate" : "05/17/2012 14:13:56"
},
{
"ACLID" : 0,
"ID" : 105,
"auditInfoVersion" : 3435973836,
"createBy" : 2,
"createDate" : "05/17/2012 14:14:13",
"isSubFolder" : 0,
"name" : "abcasdna",
"objectType" : 3,
-->"parentID" : 104,
"policyID" : 2,
"sDescription" : "",
"updateBy" : 2,
"updateDate" : "05/17/2012 14:14:13"
},
{
"ACLID" : 0,
"ID" : 106,
"auditInfoVersion" : 3435973836,
"createBy" : 2,
"createDate" : "05/18/2012 12:51:39",
"isSubFolder" : 0,
"name" : "new2",
"objectType" : 3,
-->"parentID" : 100,
"policyID" : 2,
"sDescription" : "",
"updateBy" : 2,
"updateDate" : "05/18/2012 12:51:39"
}
]
now the required type of data is:
[{
name:'Piyush1',
children: [{
name: 'New1',
children:[{
name: 'abcasdna'
}]
},{
name: 'New2'
}]
},{
name: 'New'
}]
Now the thing is that there could be any number of folders and any level of hierarchy.
so is there a way i can achieve this conversion?

MongoDB query AND/OR Precedent

In MongoDB, if I wanted to express A AND (B OR C), I can easily do by:
db.demo.find( { a: 1, $or: [ {b:1}, {c:1} ] });
But if I wanted (A AND B) OR C -- it does not seem to work. If I try:
db.demo.find( { $or: [ {a:1,b:1}, {c:1} ] });
the above is treating it as A or B or C, which is same as
db.demo.find( { $or: [ {a:1}, {b:1}, {c:1} ] });
At this point in time, I do not want to use Javascript expression $where to accomplish this (but will have no choice, if nothing else works) - the reason being, I am creating a general filter rules, which is being directly converted as MongoDB query.
Any help?
The query works actually, exactly as it should. The question is incorrect.
Here is what a view of what I tried and how it works!
Data:
> db.demo.find()
{ "_id" : 1, "age" : 38, "mgmt" : "no", "salary" : 100 }
{ "_id" : 2, "age" : 45, "salary" : 200, "mgmt" : "no" }
{ "_id" : 3, "age" : 50, "salary" : 250, "mgmt" : "no" }
{ "_id" : 4, "age" : 51, "salary" : 75, "mgmt" : "yes" }
{ "_id" : 5, "age" : 45, "salary" : 75, "mgmt" : "no" }
Query to get (Age>40 AND Salary>200) OR mgmt='yes'
> db.demo.find( { $or: [ { age: {$gt:40}, salary:{$gt:200} }, {mgmt: 'yes'} ] })
{ "_id" : 3, "age" : 50, "salary" : 250, "mgmt" : "no" }
{ "_id" : 4, "age" : 51, "salary" : 75, "mgmt" : "yes" }
Query to get (Age>40) OR (Salary>200) OR mgmt='yes'
> db.demo.find( { $or: [ { age: {$gt:40}}, {salary:{$gt:201} }, {mgmt: 'yes'} ] })
{ "_id" : 2, "age" : 45, "salary" : 200, "mgmt" : "no" }
{ "_id" : 3, "age" : 50, "salary" : 250, "mgmt" : "no" }
{ "_id" : 4, "age" : 51, "salary" : 75, "mgmt" : "yes" }
{ "_id" : 5, "age" : 45, "salary" : 75, "mgmt" : "no" }
All of them working as it should. Great!

Categories

Resources