I am trying to access JSON values. This is the JSON object:
{
"attrs": {
"width": 1728,
"height": 787,
"dragabble": true
},
"className": "Stage",
"children": [
{
"attrs": {},
"className": "Layer",
"children": [
{
"attrs": {
"stroke": "green",
"strokeWidth": "5",
"points": [
348,564.125
]
},
"className": "Line"
}
]
}
]
}
And I am trying to use these values, like points, here:
socket.on("canvas-data", function(data){
var interval = setInterval(function(){
if(isDrawing) return;
setIsDrawing(true);
clearInterval(interval);
var obj = JSON.parse(data);
setStageData(obj);
var layer = new Konva.Layer();
var lines = new Konva.Line(
{
stroke: stageData.stroke,
strokeWidth: stageData.strokeWidth,
points: stageData.points
})
layer.add(lines);
stageEl.current.add(layer);
}, 200)
})
data is the JSON string, I tried to parse data into obj, set my stageData to obj and then set the corresponding JSON attributes to the values like stroke, strokeWidth and points. This doesn't work however, they're undefined. How do I access them?
(I also tried skipping the step where I set my stageData to obj, and just use obj.stroke instead of stageData.stroke etc.)
You can just skip using setStageData() and use the parsed object directly if you wish, or just name the parsed object stageData by default.
In any case, when you have nested objects and values in an Object, you access them by using the correct index, in your case, it would look this way:
socket.on("canvas-data", function(data) {
var interval = setInterval(function() {
if (isDrawing) return;
setIsDrawing(true);
clearInterval(interval);
var stageData = JSON.parse(data);
var layer = new Konva.Layer();
var lines = new Konva.Line(
{
stroke: stageData.children[0].children[0].attrs.stroke,
strokeWidth: stageData.children[0].children[0].attrs.strokeWidth,
points: stageData.children[0].children[0].attrs.points
});
layer.add(lines);
stageEl.current.add(layer);
}, 200);
})
Doesn't look very nice, but it works. You can always use this app called JSON Path list, which shows you all the possible paths and their values in a JSON object.
Related
I have a small issue with the parameter direction of the function getConnectedNodes() based on the Vis.js documentation (search for "getConnectedNodes" in the link)
Any idea to get the direction of the edges using the parameter (i don't know how to)?
JSON Example
[
{ "x": 0, "y": 0, "id": "0", "connections": [ 2 ] // i think here should be a from?},
{ "x": 200, "y": 0, "id": "1", "connections": [ 3, 2 ] },
{ "x": 500, "y": 500, "id": "2", "connections": [ 0, 1 ] },
{ "x": 300, "y": -200, "id": "3", "connections": [ 1 ] }
]
Here part of the code
google.script.run.withSuccessHandler(([nodes, edges]) => new vis.Network(container, {nodes: nodes, edges: edges}, options)).sample();
let network;
function init() {
container = document.getElementById('mynetwork');
exportArea = document.getElementById('input_output');
network = google.script.run.withSuccessHandler(([nodes, edges]) => {network = new vis.Network(container, {nodes: nodes, edges: edges}, options);}).sample();
};
function addConnections(elem, index) {
elem.connections = network.getConnectedNodes(index); < I THINK THE PROBLEM IS HERE
}
function exportNetwork() {
var nodes = objectToArray(network.getPositions());
nodes.forEach(addConnections);
var exportValue = JSON.stringify(nodes, undefined, 2);
exportArea.innerHTML = exportValue;
}
function objectToArray(obj) {
return Object.keys(obj).map(function(key) {
obj[key].id = key;
return obj[key];
});
}
Before hand, thanks a lot!
index is the index of the array like 0, 1, 2,,,. The start index is 0. On the other hand, elem is the object like {x: ###, y: ###, id: ###}. From these situation, I thought that index of getConnectedNodes(index) might be elem.id. So how about the following modification?
From:
elem.connections = network.getConnectedNodes(index);
To:
elem.connections = network.getConnectedNodes(elem.id, "from");
From the document, if you want to retrieve "parent", you can retrieve it by adding from to the argument.
For a node id, returns an array with the id's of the connected nodes.
If optional parameter direction is set to string 'from', only parent nodes are returned.
If direction is set to 'to', only child nodes are returned.
Any other value or undefined returns both parent and child nodes.
When you want to retrieve "child", please add to to the argument instead of from.
I am translating some code from python into Javascript (I am inexperienced in JS), as part of it I need to write a JSON, currently when writing in JS it looks like this(just a brief sample):
[
{
"Num": "000000",
"Status": 1,
},
{
"Num": "00001",
"Status": 0,
},
]
However I need it to look like this:
{
"mydata": [
{
"Num": "00000",
"Status": 1,
},
{
"Num": "00001",
"Status": 0,
},
]
}
How can I adapt my code to generate this single main key for the whole JSON, here is what I have so far:
var jsondata = []
for (result in results) {
jsondata.push({
'Num' : idnum,
'Status': results[result].StatusID,
})
}
let data = JSON.stringify(jsondata, null, 2)
fs.writeFileSync('testingjson.json', data)
This code here sits in a for loop, so I cannot just write the key in the push, it would generate the mydata key for every iteration of the loop.
I need to know how I can pre-define the mydata, has anyone got a good method to do this?
Just define mydata as an array, and then at the end, create an object where mydata is one of the keys:
const mydata = []
for (const result in results) {
mydata.push({
'Num' : idnum,
'Status': results[result].StatusID,
});
}
const json = JSON.stringify({ mydata }, null, 2);
If you want to use a different key name, then change it when stringifying, eg:
const json = JSON.stringify({ someKeyName: mydata }, null, 2);
If results is an object, then you can make the code more concise with Object.values and map:
const Num = idnum;
const mydata = Object.values(results)
.map((item => ({ Num, Status: item.StatusID }));
const json = JSON.stringify({ mydata }, null, 2);
fs.writeFileSync('testingjson.json', data)
I have a sample json data,which I need to add in to different collections in mongodb.But I dont want whole json data.For example,
jsondata=
{"widget": {
"debug": "on",
"window": {
"title": "Sample Konfabulator Widget",
"name": "main_window",
"width": 500,
"height": 500
},
"image": {
"src": "Images/Sun.png",
"name": "sun1",
"hOffset": 250,
},
"text": {
"data": "Click Here",
"size": 36,
"style": "bold",
}}
In this json I want window key in one collection,simillarly image key in another mongo collection.
So I was thinking if I can save that key value pair in one variable,then I can add that variable in to collection.For this I was trying for each
var jsondat=JSON.parse(jsondata);
for(var exKey in jsondat) {
console.log("entering");
var b=stringdata[exKey].image;
console.log(b);
}
But I was unable to get that image key data.Is this the right approach for this?can someone help me out in this.
My expected result would be:
In one variable,The value of window key should be saved in json format.
Simillarly image and text keyvalues in another variables.
Thanks.
Why aren't you fetching window and image simply from the object as key like:
var window= jsondata.widget.window;
var image = jsondata.widget.image;
and save them in mongo db
db.window.insert(window)
db.image.insert(image)
Tell me If I understand it right.
I don't see much problem.
var jsondat=JSON.parse(jsondata);
for(var exKey in jsondat.widget) {
console.log("entering");
console.log(exKey);
if(exKey === 'image'){
db.image.insert(jsondat.widget[exKey]);
}else if(exKey === 'window'){
db.window.insert(jsondat.widget[exKey]);
}
// or db.getCollection(exKey).insert(jsondat.widget[exKey]);
}
But I would also add that normalization is not desirable in MongoDB, you should use embedding more because you won't be able to join collections later on if you want to collate data. But that's a general idea, maybe in your requirement you want different collection.
You can do it in several ways.
Method#1
var arr = [];
for(var i in jsondata.widget){
if(typeof(jsondata.widget[i])==='object'){
arr.push(jsondata.widget[i]);
}
};
console.log(arr);
Method#2
You can use unserscore utility library to get in easy
var _=require('underscore');
var arr = [];
_.each(jsondata.widget,function(o){
if(typeof(o)==='object'){
arr.push(o);
}
});
console.log(arr);
Now you can access all the object by index
Output
[ { title: 'Sample Konfabulator Widget',
name: 'main_window',
width: 500,
height: 500 },
{ src: 'Images/Sun.png', name: 'sun1', hOffset: 250 },
{ data: 'Click Here', size: 36, style: 'bold' } ]
Method#3
Try to get separate value of each inner keys
var window= jsondata.widget.window;
var image= jsondata.widget.image;
var text= jsondata.widget.text;
Edit
var obj={
"json": {
"window": {
"title": "sample",
"name": "sam"
},
"image": {
"src": "Images/Sun.png",
"name": "sun1",
"hOffset": 250
}
}
}
console.log(obj.json.window)
result-> {title: "sample", name: "sam"}
I decided it would be a fun project to see if i could take data from Google Analytics and display that in a custom dashboard, and hopefully learn a thing or two about using json, and javascript.
after a lot of debugging i now managed to pull the data from the Google Analytics server with their php api, and save the output into data.json on the server.
below the data.json, it's valid as per JSONLint.com:
{
"0": {
"date": "20160113",
"pageviews": "46",
"sessions": "21"
},
"1": {
"date": "20160114",
"pageviews": "66",
"sessions": "18"
},
"2": {
"date": "20160112",
"pageviews": "50",
"sessions": "14"
},
"3": {
"date": "20160116",
"pageviews": "19",
"sessions": "14"
},
"4": {
"date": "20160117",
"pageviews": "23",
"sessions": "14"
},
"5": {
"date": "20160115",
"pageviews": "38",
"sessions": "11"
},
"6": {
"date": "20160118",
"pageviews": "35",
"sessions": "9"
},
"7": {
"date": "20160119",
"pageviews": "15",
"sessions": "7"
}
}
Now i've tried to use the data from data.json and feed it into chartist's labels/series in order to draw a graph.
var labelArray = [];
var seriesArray = [];
var labelOutput = [];
$.getJSON("data.json", function(json) {
//var jsonObj = JSON.parse(json);
for (var i in json){
labelArray.push(json[i].date);
};
for (var i in json){
seriesArray.push(json[i].sessions);
};
// var myData = {
// labels:
// }
// labelOutput = labelArray.join(',')
// seriesOutput = serieArray.join(',')
console.log(labelArray);
console.log(seriesArray);
// this will show the info it in firebug console
});
new Chartist.Line('.ct-chart', {
labels: [labelArray],
series: [[seriesArray]]
});
However I'm currently out of ideas why this would not work, the labels on X and Y axis are correctly shown, but no graph shows up.
I've tried using .join to see if that makes a difference, but using labelOutput instead of labelArray also doesn't change anything.
In the console the array that is being fed into chartist seems all right to me, if I copy paste it from the console into the script everything works.
Current output for labelArray and seriesArray:
labelArray
Array [ "20160113", "20160114", "20160112", "20160116", "20160117", "20160115", "20160118", "20160119" ]
seriesArray
Array [ "21", "18", "14", "14", "14", "11", "9", "7" ]
Anyone knows why chartist.js does manage to add the correct labels along the axes but fails to read the same data and draw the chart?
Although the answer by #mnutsch works, there is an easier way to add dynamic content into the chart.
You can simply add the arrays directly as parameters, which I think is what the OP was trying to do.
response object would be the ajax data
var seriesVals = [];
var labelsVals = [];
for (var i = 0; i < response.length; i++) {
seriesVals.push(response[i].total);
labelsVals.push(response[i].response_code);
}
var pieData = {
series: seriesVals,
labels: labelsVals
};
In case anyone comes across this later, you can also do it like this:
//Create javascript arrays with the values and labels, replace this with code to read from the database/API/etc.
var array_1_values = [100, 120, 180, 200, 90]; //these are the values of the first line
var array_2_values = [20, 35, 65, 125, 245]; //these are the values of the second line
var array_labels = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']; //these are the labels that will appear at the bottom of the chart
//create a prototype multi-dimensional array
var data_chart1 = {
labels: [],
series: [
[],
[]
]
};
//populate the multi-dimensional array
for (var i = 0; i < array_1_values.length; i += 1)
{
data_chart1.series[0].push(array_1_values[i])
data_chart1.series[1].push(array_2_values[i])
data_chart1.labels.push(array_labels[i])
}
//set the size of chart 1
var options_chart1 = {
width: '300px',
height: '200px'
};
//create chart 1
new Chartist.Line('#chart1', data_chart1, options_chart1);
In case anyone else stumbles upon the problem, below is what I came up with to get it to work.
After another day of trail and error i managed to pinpoint the problem.
The problem was:
In the original situation I tried to use a plain array as input for both labels and series. However, Chartist requires objects to render the labels/series as well as the graph.
The below works for me pulling the data from the data.json, adding it to an object and provide it to chartist.
var labelArray = {};
var seriesArray = {};
var labelOutput = [];
var Output
// $.getJSON("data.json", function(json) {
$.ajax({
url: 'data.json',
async: false,
dataType: 'text',
success: function(json) {
labelArray = JSON.parse(json);
data = {
labels:
[
labelArray[0].date,
labelArray[1].date,
labelArray[2].date,
labelArray[3].date,
labelArray[4].date,
labelArray[5].date,
labelArray[6].date
],
series: [[
labelArray[0].sessions,
labelArray[1].sessions,
labelArray[2].sessions,
labelArray[3].sessions,
labelArray[4].sessions,
labelArray[5].sessions,
labelArray[6].sessions
]]
}
}
});
new Chartist.Line('.ct-chart', data);
Decided to go with $.ajax to get the json file rather than getJSON as this allows me to disable asynchronous loading, ensuring the data is available when the graph is drawn.
Also, it is possible to set the dataType to Json rather than text, but this gives error in the JSON.parse line. Assuming that is because it tries to parse json as json, and fails to do so. But this is the only way i managed to get it to work, and add the json to an object.
Most likely the whole labelArray[0].date, labelArray[1].date is rather inefficient and should be improved but it works for now.
This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 8 years ago.
I have a JSON string that looks like this:
[
{
"id": "acbPreviewCell",
"width": 80
},
{
"id": "advName",
"width": 170
},
{
"id": "adHeadline",
"width": 150
},
{
"id": "adSize",
"width": 150
},
{
"id": "adProduct",
"width": 150
},
{
"id": "adCategory",
"width": 150
},
{
"id": "adSection",
"width": 150
},
{
"id": "adColor",
"width": 150
},
{
"id": "adTags",
"width": 150
},
{
"id": "adRegions",
"width": 150
},
{
"id": "adStatus",
"width": 150
},
{
"id": "adCreated",
"width": 150
},
{
"id": "adBookingNb",
"width": 150
},
{
"id": "adPickup",
"width": 150
},
{
"id": "folioMeta",
"width": 150
}
]
To help explain further, each of these entries is the ID of a table header, along with the width of that table header. I'm using it within an application so that I can remember a user's custom column width that they set.
I would like to break this JSON string down into a javascript array, so that I can easily access each ID and it's width.
Any help would be appreciated with setting it up as an array and then breaking it down to access the ID and the width. Thank you!
If you want to convert it to an array you can use the built-in JSON object to parse it: JSON.parse(yourString).
But if you want to easily access values by ID, you will have to actually convert it to an object:
var originalData = JSON.parse(yourString);
var parsedData = {};
for (var i = 0, l = originalData.length; i < l; i++) {
parsedData[originalData[i].id] = originalData[i].width;
}
// now you can easily access the wanted widths
var acbPreviewCellWidth = parsedData['acbPreviewCellWidth'];
Someone else mentioned a hashed map, which is pretty much what I'm guessing you need. That is to say, you want to access by id quickly as in array['advName'] gives you the width there.
You could mill through the values you get like so:
a = [
{
"id": "acbPreviewCell",
"width": 80
},
{
"id": "advName",
"width": 170
},
{
"id": "adHeadline",
"width": 150
}
];
function rewrite_array(arr){
new_arr = new Array();
for( i=0; i<a.length; i++){
new_arr[arr[i]['id']] = arr[i]['width'];
}
return new_arr;
}
n = rewrite_array(a);
console.log(n["advName"]);
console.log(a[1]['width']);
In theory, it already is stored as an array. However, if you would like to parse the JSON object to ensure that it is properly formed, use var jsonArray = JSON.parse(jsonString); No jQuery is needed.
Use jQuery.parseJSON(jsonString)
You might want to get the JSON using ajax, and then loop through all the values lushing them to an array in javascript, or you can simply call var objArr = $.parseJSON('file'); to get an array of all the objects. If you want to fet the values, you van simply get them using objArr[index].val.
Using this you can call, for instance, the first objects values like this.
var id = objArr[0].id;
var width = objArr[0].width;
Try
function filtered(v) {
return $.map(json, function(value) {
return value.id === v ? value : null
})[0];
};
usage
filtered("folioMeta"); // do stuff with "folioMeta" object within array
filtered("folioMeta").id // `"folioMeta"`
filtered("folioMeta").width // `150`