Programmatically create json - javascript

This is the JSON I'm trying to create programmatically:
{
"sensors": [{
"x": 342,
"y": 213,
"id": 4
}, {
"x": 642,
"y": 913,
"id": 3
}, {
"x": 452,
"y": 113,
"id": 2
}]
}
I have to iterate through all elements with a specific class to retrieve the data for the json:
$(".marker").each(function()
{
var x = $(this).attr("data-x");
var y = $(this).attr("data-y");
var id = $(this).attr("data-id");
});
How could I create the json object to be like I described?

Try this
var json = {"sensors":[]};
$(".marker").each(function()
{
var x = $(this).attr("data-x");
var y = $(this).attr("data-y");
var id = $(this).attr("data-id");
json.sensors.push({"x":x, "y":y,"id":id});
});

Look JSON.parse method on MDN ou MSDN
var jsontext = '{"firstname":"Jesper","surname":"Aaberg","phone":["555-0100","555-0120"]}';
var contact = JSON.parse(jsontext);
document.write(contact.surname + ", " + contact.firstname);
// Output: Aaberg, Jesper

Related

How to target only X or Y value in jsonObj array

I am using a method as found here with chartJS to input dates that are missing from a JSON response.
jsonObj["result"]["data"] is output from the initial JSON response:
{
"action": "data_link_day",
"result": {
"url_ending": "0",
"data": [{
"x": "2018-03-12",
"y": 3
}, {
"x": "2018-03-16",
"y": 5
}]
}
}
Inside the drawChart function, I need to separate the x/y values as graphData = y (number) and labels = x (date) by targeting them individually. I tried to do jsonObj["result"]["data"].x but obviously not correct.
function drawChart(jsonObj) {
var graphData = jsonObj["result"]["data"],
labels = jsonObj["result"]["data"];
for (var i = 0; i < labels.length; i++) {
//make sure we are not checking the last date in the labels array
if (i + 1 < labels.length) {
var date1 = moment(labels[i], "YYYY-MM-DD");
var date2 = moment(labels[i + 1], "YYYY-MM-DD");
//if the current date +1 is not the same as it's next neighbor we have to add in a new one
if (!date1.add(1, "days").isSame(date2)) {
//add the label
labels.splice(i + 1, 0, date1.format("YYYY-MM-DD"));
//add the data
graphData.splice(i + 1, 0, 0);
}
}
}
...
}
You can use the following code to separate your data into X and Y arrays:
let data = jsonObj.result.data;
let dataX = data.map(data => data.x);
let dataY = data.map(data => data.y);
Demo:
const json = `
{
"action": "data_link_day",
"result": {
"url_ending": "0",
"data": [{
"x": "2018-03-12",
"y": 3
}, {
"x": "2018-03-16",
"y": 5
}]
}
}`;
const input = JSON.parse(json);
let data = input.result.data;
let dataX = data.map(data => data.x);
let dataY = data.map(data => data.y);
console.log(dataX);
console.log(dataY);

Dimple.js doesn't like my Array

I have data.json in this format:
{
"Users": [
{
"userName": "Herbie",
"weigh-in data": [
{ "date": "2016.01.04", "weight": "114.3" },
{ "date": "2016.01.05", "weight": "114.6" },
{ "date": "2016.01.06", "weight": "114.9" }
]
},
{
"userName": "Wayne",
"weigh-in data": [
{ "date": "2016.02.01", "weight": "120.3" },
{ "date": "2016.02.05", "weight": "123.6" },
{ "date": "2016.02.06", "weight": "123.9" }
]
}
]
}
// etc., more user objects
In my application: a selection of a user is made, an ajax call gets this data, I loop thru it to get only the selected user's weigh-in data, and I'm successfully rendering this data to a table.
Now I'm trying to use the same result in a Dimple chart but Dimple evidently doesn't like my chartData array:
var dataObj = JSON.parse(jsonData);
var usersArray = dataObj.Users;
var chartData = [];
// etc. SNIP
for (var obj of usersArray) {
if (obj.userName === selUser) { // weigh-ins of the selected user only
dataRows.innerHTML = "";
for (var i = 0, j = selUserData.length; i < j; i++) {
var dataDate = selUserData[i].date;
var dataWeight = selUserData[i].weight;
chartData.push('{ "User"' + ': ' + '"'+selUser+'", ' + '"Date":' + ' ' + '"'+dataDate+'", ' + '"Weight":' + ' ' + '"'+dataWeight+'" }');
// SNIP: build rows from the data, load up the table, no problem
dataRows.innerHTML += row;
} // selUserData loop
var svg = dimple.newSvg("#chartContainer", 800, 600);
var chart = new dimple.chart(svg, chartData);
chart.setBounds(60, 30, 505, 305);
var x = chart.addCategoryAxis("x", "Date");
x.addOrderRule("Dates");
var y = chart.addCategoryAxis("y", "Weight");
y.addOrderRule("Weights");
var s = chart.addSeries("weigh-ins", dimple.plot.line);
chart.draw();
... which results in a non-chart. However, if I console.log or alert(chartData) and set the result as chartData, i.e.:
var chartData = [
{ "User": "Wayne", "Date": "2016.02.01", "Weight": "180.3" },
{ "User": "Wayne", "Date": "2016.02.05", "Weight": "123.6" },
{ "User": "Wayne", "Date": "2016.02.06", "Weight": "153.9" }
]
... then I get a chart, ergo my confusion.
Any insight greatly appreciated,
Whiskey
You're pushing the JSON into your array as strings not objects, it should be:
chartData.push({ "User": selUser, "Date": dataDate, "Weight": dataWeight });
Which has the added benefit of being much easier to read!

How to convert Json string with key-value pair into string with only values in javascript

How to convert JSON string with key-value pair into string with only values in javascript.
For example my JSON output looks like this
{
"data": {
"BearCollection": {
"BearDetails": [
{
"Name": "James",
"x": "81.43410000",
"y": "6.32813300"
},
{
"Name": "James",
"x": "81.43489000",
"y": "6.32763300"
},
{
"Name": "Sera",
"x": "81.4377000",
"y": "6.32453300"
}
]
}
},
"xhr": {}
}
I want to convert it using javascript as
var details=[
[
"James",
81.4341,
6.328133
],
[
"James",
81.43489,
6.327633
],
[
"Sera",
81.4377,
6.324533
]
];
Is there any way to do this?
var json = "Your JSON string";
obj = JSON.parse(json);
for(int i= 0; i< obj.data.BearCollection.BearDetails.length;i++)
{
String Name = obj.data.BearCollection.BearDetails[i].Name;
String x = obj.data.BearCollection.BearDetails[i].x;
String y = obj.data.BearCollection.BearDetails[i].y;
..fill Array (pseudo - do some work yourself ;) )
}
$(document).ready(function() {
var data = JSON.parse('{"data": {"BearCollection": {"BearDetails": [{"Name": "James","x": "81.43410000","y": "6.32813300"},{"Name": "James","x": "81.43489000","y": "6.32763300"},{"Name": "Sera","x": "81.4377000","y": "6.32453300"}]}},"xhr": {}}');
var bear;
var arr = [];
var nestedArr;
for (i in data.data.BearCollection.BearDetails) {
bear = data.data.BearCollection.BearDetails[i];
nestedArr = [];
nestedArr.push(bear.Name);
nestedArr.push(bear.x);
nestedArr.push(bear.y);
arr.push(nestedArr);
}
});
Use JSON.parse to get the object from the JSON string, then access the BearDetails, convert each element to an array, and stringify the new collection again:
var obj = JSON.parse(jsonstring);
var details = obj.data.BearCollection.BearDetails.map(function(detail) {
return [detail.Name, detail.x, detail.y];
});
return JSON.stringify(details);

Create an object with custom structure in javascript

I need to create an array object with this exact structure:
{"item1": {
0 : {
color:"description1",
width:"description2",
height:"description3"
}
1 : {
color:"description1",
width:"description2",
height:"description3"
}
//and so on
},
"item2": {
0 : {
color:"description1",
width:"description2",
height:"description3"
}
//and so on
}
//and so on
}
Estatically works fine. Now, I want to make it dinamically. So, the main question is... How can I loop the data while constructing the object at the same time?
This is an example of the incoming object I work from:
[
{
"uid": 1,
"legendname": "item1",
"rows": [
{
"uid": 0,
"color": "482400",
"width": "482400",
"height": "25"
},
{
"uid": 1,
"color": "587898",
"width": "789658",
"height": "30"
}
]
}
{
"uid": 2,
"legendname": "item2",
"rows": [
{
"uid": 0,
"color": "482400",
"width": "482400",
"height": "25"
}
]
}
]
How can I loop the data while constructing the object at the same time?
Is not clear. But if you want to create a new structure based on the incoming one, you can use this:
// ar = your incoming object
// b_obj = your result
var b_obj = {}
for (var i = 0; i < ar.length; i++)
{
item = ar[i];
b_item = {};
for (var i_row = 0; i_row < item.rows.length; i_row++)
{
var row = {};
row.color = item.rows[i_row].color;
row.width = item.rows[i_row].width;
row.height = item.rows[i_row].height;
b_item[i_row] = row;
}
b_obj[item.legendname] = b_item;
}

converting format of JSON

I am using an AJAX query to Fuseki, that I want to visualize in a D3.js collapsable tree. However Fuseki returns the JSON in a format that the D3.js code does not recognise. like this:
{
"head": {
"vars": [ "s" ]
} ,
"results": {
"bindings": [
{
"s": {
"type": "uri",
"value": "http://www.co-ode.org/ontologies/pizza/2005/05/16/pizza.owl#FourCheesesTopping"
},
"p": {
"type": "uri",
"value": "http://www.w3.org/2000/01/rdf-schema#subClassOf"
},
"o": {
"type": "uri",
"value": "http://www.co-ode.org/ontologies/pizza/2005/05/16/pizza.owl#CheeseTopping"
}
]
}
}
I need to convert this JSON into this format:
{
"name": "Pizza",
"children": [
{
"name": "http://www.co-ode.org/ontologies/pizza/2005/05/16/pizza.owl#PizzaBase",
"children": [
]
},
{
"name": "http://www.co-ode.org/ontologies/pizza/2005/05/16/pizza.owl#PizzaTopping",
"children": [
{
"name": "http://www.co-ode.org/ontologies/pizza/2005/05/16/pizza.owl#MeatTopping",
"children": [
{
"name": "http://www.co-ode.org/ontologies/pizza/2005/05/16/pizza.owl#HotSpicedBeefTopping"
}
]
}
]
}
]
}
I have tried taking the JSON and putting it into a new object with the correct format, but it is not working. Here is my code:
var parent = new Object();
var childArray=[];
var child = [];
function createChildObj(_children, children, depth, id, childName, parent, x, x0, y, y0){
var childObj = new Object();
childObj._children = _children;
childObj.children = children;
childObj.depth = depth;
childObj.id =id;
childObj.name = childName;
childObj.parent= parent;
childObj.x = x;
childObj.x0 = x0;
childObj.y = y;
childObj.y0 = y0;
return childObj;
};
console.log(root.length)
for (var i=0; i<root.length; i++){
var childName = root[i]["s"]["value"];
var childObj = createChildObj("children",null, 1, 2, childName, parent, 190, 190, 180, 180);
child.push(childObj);
}
parent.name = "Pizza";
parent.depth = 0;
parent.id = 3;
parent.children= child;
parent.x0 = root.x0;
parent.x = parent.x0;
parent.y0 = root.y0;
parent.y = parent.y0;
So I am aiming to have parent as the JSON object with the data in the correct format to parse to the d3. sorry its a mess, been fiddling for ages trying to learn D3, and the learning curve is steeper than I had anticipated. Any help would be great! cheers.

Categories