I am using C3 library for the first time and I think it's a good alternative to D3 for designing simple and reusable charts with no pain.
However, I have some issues in designing a timeseries chart.
Here is an example of the JSON file I will use to generate my chart:
data: {
json: [
{
"city": "Paris",
"date": "2016-09-01",
"event": 234
},
{
"city": "Paris",
"date": "2016-09-02",
"event": 891
},
{
"city": "Paris",
"date": "2016-09-03",
"event": 877
},
{
"city": "Berlin",
"date": "2016-09-01",
"event": 190
},
{
"city": "Berlin",
"date": "2016-09-02",
"event": 234
},
{
"city": "Berlin",
"date": "2016-09-03",
"event": 231
},
{
"city": "London",
"date": "2016-09-01",
"event": 23
},
{
"city": "London",
"date": "2016-09-02",
"event": 12
},
{
"city": "London",
"date": "2016-09-03",
"event": 89
},
],
The problem is that I can not set both my axis x: as a timeseries type and the key "city" as a category type.
For now I have:
keys: {
x: 'period',
value: ['event'],
},
axis: {
x: {
type: 'timeseries',
tick: {
format: '%Y-%m-%d'
}
}
},
type: 'spline'
And the corresponding Plunker: http://plnkr.co/edit/T1aLWQpaFwdu2zsWCa3d
I would like to have 3 splines, corresponding to the 3 cities that are retrieved from the JSON file.
Can you help me achieve this ?
Thank you very much :)
You need to wrangle your data into a format that c3 finds acceptable, which is akin to the example here -->https://jsfiddle.net/maxklenk/k9Dbf/
For yours we'd need an array of entries like
[{
date = val
London = val
Paris = val
Berlin = val
},
...
]
To do that we need to manipulate the original json:
var json = <defined here>
// group json by date
var nestedData = d3.nest().key(function(d) { return d.date; }).entries(json);
var cities = d3.set(); // this keeps a record of the cities mentioned so we don't need to hard-code them later on
// run through the dates and make new objects of city=entry pairs (and the date=whatever)
// all stored in a new array (formattedData) which we can feed to the chart json argument
var formattedData = nestedData.map (function (entry) {
var values = entry.values;
var obj = {};
values.forEach (function (value) {
obj[value.city] = value.event;
cities.add(value.city);
})
obj.date = entry.key;
return obj;
});
var chart = c3.generate({
data: {json: formattedData,
keys: {
x: 'date', // it's possible to specify 'x' when category axis
value: cities.values(),
}
},
...
See the edited plunkr at http://plnkr.co/edit/5xa4z27HbHQbjcfpRLpQ?p=preview
Related
I have JSON structure like this
"timebought": "2021-01-01T00:00:00",
"totalCost": 3000.0,
"address": "ABC",
"status": false,
"customersEmail":"nguyenvana#gmail.com",
"orderDetails": [
{
"productId": "A1",
"amount": 5
},
{
"productId": "A2",
"amount": 5
}
]
If I want make a JSON for post, how do i do it? I mean the child object "orderDetails", can you give me an example?
I found out how to do it:
First, make a function return list Child:
function toArr(){
let arr = [];
prodList.forEach((prod) => {
let item ={"id":prod.id,"amount" : prod.quantity};
arr = [...arr,item];
});
console.log(arr);
return arr;}
and then
const body = JSON.stringify({
customersEmail : e.target.email.value,
totalCost : totalCost.current,
status : false,
address: e.target.address.value,
orderDetails: toArr()
});
How can we loop through given JSON object to traverse all its properties:
<script type="text/javascript">
var students = '{"name": "John", "age": 30, "subjects": [{ "name": "IT", "marks": 85 }, { "name": "Maths", "marks": 75 }, { "name": "English", "marks": 60 }]}';
var myObj = JSON.parse(students);
alert(myObj.name);
alert(myObj.age);
alert(myObj.subjects[0]['name']);
alert(myObj.subjects[0]['marks']);
alert(myObj.subjects[1]['name']);
alert(myObj.subjects[1]['marks']);
alert(myObj.subjects[2]['name']);
alert(myObj.subjects[2]['marks']);
</script>
You can see I am accessing nested "subject" properties by using its index and property name. But the code becomes lengthy to traverse each items. To avoid it, I am wondering how to loop (e.g. for in loop) through by writing single line of code to access all its properties?
You could do this:
var myObj = JSON.parse(students);
for(var index = 0; index < myObj.subjects.length; index++) {
alert(myObj.subjects[index]['name']);
alert(myObj.subjects[index]['marks']);
}
Just use Each function to iterate the each subjects
var students = '{"name": "John", "age": 30, "subjects": [{ "name": "IT", "marks": 85 }, { "name": "Maths", "marks": 75 }, { "name": "English", "marks": 60 }]}';
var myObj = JSON.parse(students);
$.each(myObj['subjects'], function(index, value) {
console.log(value['name']+" "+ value['marks']);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
try using stringify
var myObj = JSON.stringify(students);
for(var index=0;index < myObj.subjects.length;index++) {
alert ( myObj.subjects[index] );
}
I have a JSON file with the following format:
const data = [
{
"quantity": "200",
"prodType": "stock",
"symbol": "LOL",
"prodDesc": "Εθνική τράπεζα",
"market": "Greece",
"averageCost": "131,16",
"totalCost": "123,47",
"lastPrice": "121,123",
"value": "123,34",
"positionPercentage": "10",
"valueEUR": "113,23",
"pl": "1300",
"plPercentage": "12",
"plEuro": "1238",
"results": "12-01-2017",
"dividend": "12-03-2017",
"isin": "1234566"
}
]
I want to filter the data using their Product Type.
As a result, im creating an action
export function fetchSearchData(product_type) {
const filtered_data = data.filter(record=>
{
return record.prodType.match(product_type)
});
return {
type: FETCH_SEARCH_DATA,
payload: filtered_data
};
}
But it does not seem to work. Do you have any idea why?
I came to read the json file to output to an highcharts.
I have a highcharts areagraph whose values are received from json whose format is as follows:
scope.jsondata = [
{
"Name": "A",
"Categories": "03.01",
"Locate": "1",
"Value": 30
},
{
"Name": "A",
"Categories": "03.02",
"Locate": "1",
"Value": 50
},
{
"Name": "A",
"Categories": "03.03",
"Locate": "1",
"Value": 60
},
{
"Name": "A",
"Categories": "03.04",
"Locate": "1",
"Value": 40
},
{
"Name": "A",
"Categories": "03.05",
"Locate": "1",
"Value": 70
}
];
How can I embed those values for my jsondata in angularJS?
scope.render = function (data) {
var target = element.find('#detail-usage-chart'),
firstDate = {
name: scope.jsondata.Name,
data: scope.jsondata.Vaule,
color: '#f48d7f',
type: 'area'
},
tempOption = {
data: [10, 13, 17, 8, 11, 5, 11, 13 ,16, 18, 20, 13, 16, 21, 19],
type: 'spline',
yAxis: 1
}
};
Please provide a suitable way to embed the data from json.
Area chart is expecting a name and an array contaning values in its series:
See here
So all you have to do is just a quick function in order to prepare your data that way. For example:
var scope.readyValues = [];
for(var i=0;i<scope.jsondata.length;i++)
{
scope.readyValues.push(scope.jsondata[i].Value);
}
Next, just configure the series this way:
// .....chart options
series: [{
name: scope.jsondata[0].Name,
data: scope.readyValues
}
If you have multiple Names in your scope.jsondata then you can use jquery map function or you can make an array for each name.
And since you're using angular I recommend you use Highcharts-ng it's easier ;)
This is the json object I am working with
{
"name": "John Smith",
"age": 32,
"employed": true,
"address": {
"street": "701 First Ave.",
"city": "Sunnyvale, CA 95125",
"country": "United States"
},
"children": [
{
"name": "Richard",
"age": 7
},
{
"name": "Susan",
"age": 4
},
{
"name": "James",
"age": 3
}
]
}
I want this as another key-value pair :
"collegeId": {
"eventno": "6062",
"eventdesc": "abc"
};
I tried concat but that gave me the result with || symbol and I cdnt iterate. I used spilt but that removes only commas.
concattedjson = JSON.stringify(JSON.parse(json1).concat(JSON.parse(json2)));
How do I add a key pair value to an existing json object ?
I am working in javascript.
This is the easiest way and it's working to me.
var testJson = {
"name": "John Smith",
"age": 32,
"employed": true,
"address": {
"street": "701 First Ave.",
"city": "Sunnyvale, CA 95125",
"country": "United States"
},
"children": [
{
"name": "Richard",
"age": 7
},
{
"name": "Susan",
"age": 4
},
{
"name": "James",
"age": 3
}
]
};
testJson.collegeId = {"eventno": "6062","eventdesc": "abc"};
Just convert the JSON string to an object using JSON.parse() and then add the property. If you need it back into a string, do JSON.stringify().
BTW, there's no such thing as a JSON object. There are objects, and there are JSON strings that represent those objects.
You need to make an object at reference "collegeId", and then for that object, make two more key value pairs there like this:
var concattedjson = JSON.parse(json1);
concattedjson["collegeId"] = {};
concattedjson["collegeId"]["eventno"] = "6062";
concattedjson["collegeId"]["eventdesc"] = "abc";
Assuming that concattedjson is your json object. If you only have a string representation you will need to parse it first before you extend it.
Edit
demo for those who think this will not work.
const newTestJson = JSON.parse(JSON.stringify(testJson));
newTestJson.collegeId = {"eventno": "6062","eventdesc": "abc"};
testJson = newTestJson;