How to open json file with objects in d3? [duplicate] - javascript

This question already has answers here:
How do I loop through or enumerate a JavaScript object?
(48 answers)
Closed 6 years ago.
I want to load one json file for a d3 world map (based on: http://datamaps.github.io/) and a d3 bar chart (based on: https://bl.ocks.org/mbostock/3885304).
My JSON looks like this:
{
"CHE": {"costOfLivingIndex": "123.10", "propertyPriceToIncomeRatio": "123.10", "qualityOfLifeIndex": "208.54", "name": "Switzerland", "purchasingPower": "178.74", "pollutionIndex": "28.73", "trafficCommuteTimeIndex": "8.57", "health Care Index": "68.88", "climateIndex": "23.02", "safetyIndex": "74.27"},
"DNK": {"costOfLivingIndex": "84.88", "propertyPriceToIncomeRatio": "84.88", "qualityOfLifeIndex": "206.49", "name": "Denmark", "purchasingPower": "142.14", "pollutionIndex": "25.64", "trafficCommuteTimeIndex": "5.85", "health Care Index": "81.89", "climateIndex": "29.93", "safetyIndex": "74.33"}
etc...
}
I choose this lay for the d3 world map. However, how I am wondering how I can iterate through properties of the objects. If I do for instance:
console.log(data.DNK.name);
I get the name, but how can get a list with all the names (or other values)?

we you could do something like:
for (var key in data) {
alert(key + " -> " + data[key]);
}
you should be able to get the other parameters via data[key]

As it is already JSON object you can loop through it without using JSON.parse which you would use if it were string or sth.
for(var key in data){
console.log(key);
for(var k in data[key]){
console.log(k,data[key][k]);
}
}

Related

How to make the Select option appending with html? [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed last year.
Am making an select option from ajax success. The problem is that, the results are array so i need to manipulate the array with some html.
My appending code:
data = [['2022-02-01', '2022-02-02'],['2022-03-01', '2022-03-02'],['2022-04-01', '2022-04-02']]
$("#id_course").change(function () {
$('select[id=id_intakes]').empty().prepend("<option></option>");
$.each(data, function(index, date){
$('select[id=id_intakes]').append(
$('<option></option>').attr("value",date).text(date)
)
});
})
Just creates the select correctly, but it displays the array as it is. The dropdown contains all the three values array
['2022-02-01', '2022-02-02']
['2022-03-01', '2022-03-02']
['2022-04-01', '2022-04-02']
I need to manipulate this like
From:2022-02-01 & To:2022-02-02
From:2022-03-01 & To:2022-03-02
From:2022-04-01 & To:2022-04-02
So how to do this ?
You can add this to your code:
name = `From:${name[0]} & To:${name[1]}`;
Demo
data = [
['2022-02-01', '2022-02-02'],
['2022-03-01', '2022-03-02'],
['2022-04-01', '2022-04-02']
]
$('select#id_intakes').empty().prepend("<option></option>");
$.each(data, function(index, name) {
name = `From:${name[0]} & To:${name[1]}`;
$('select[id=id_intakes]').append(
$('<option></option>').attr("value", name).text(name)
)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="id_intakes"></select>

Read a JSON list in list [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 6 years ago.
I have a json like this :
{
"Project
[id=1, dateDebut=2017-01-13, dateFin=2017-01-18, description=qsd, sponsor=qsd ]"
:
[
{"id":1,"title":"qsd ","description":"qsdqsd","dateFin":"2017-01-26"},
{"id":2,"title":"sss ","description":"sss","dateFin":"2017-01-26"}
]
}
originated from : return new ObjectMapper.write(Map<Project,List<Task>> projectTasks = new LinkedMultiValueMap<>()) ;
EDIT : this is the real response :
{"Project [id=1, name=qsdsqd, type=null, done=false, dateDebut=2017-01-13, dateFin=2017-01-18, description=qsd, sponsor=qsd, client=qsd, showable=true]":
[{"id":1,"title":"qsd ","description":"qsdqsd","dateFin":"2017-01-26","dateDebut":"2017-01-14","period":null,"done":false,"status":"Actif","priority":"Normal"},
{"id":2,"title":"task 2 ","description":"qsdqsd","dateFin":"2017-01-26","dateDebut":"2017-01-14","period":null,"done":false,"status":"Actif","priority":"Normal"}]}
How can I read the list of tasks in the client side ?
First of all, your JSON is not valid. Are you sure that is a line break between the word Project and [id...]. A valid JSON would be:
{
"Project [id=1, dateDebut=2017-01-13, dateFin=2017-01-18, description=qsd, sponsor=qsd, ]":
[
{"id":1,"title":"qsd ","description":"qsdqsd","dateFin":"2017-01-26"},
{"id":2,"title":"sss ","description":"sss","dateFin":"2017-01-26"}
]
}
You can have object key names like that. But i'ts not very friendly to retrieve data.
If you cannot change your data schema (or just don't want), you can iterate over the Object with the
Object.keys(obj).forEach ( (key) => {
console.log('key: ' + key);
console.log('value: ' + obj[key]);
/* you can iterate over your value (tasks) here */
obj[key].forEach( (task) => {
console.log('task1: ', task);
});
}); //where obj is your json
Or you can access the first object property with:
obj[Object.keys(obj)[0]]; //where obj is your json
EDIT As pointed by #André Dion, forEachis best suited to iteration, not map. And we're assuming your response is already parsed from the server (by yourself or by a lib like jquery). If not, you should do a JSON.parse(response); to retrieve the object.
You may try this:
Assume above response in stored in var response.
for(var project in response) { // this will get every project
for(var i=0; i<project.length; i++) { // this will iterate over the array for each project which are your tasks.
console.log("task" + project[i]);
console.log(project[i]["id"]); // access each tasks id, similar for other attributes
}
}

How to pass a variable in to the JSON search loop? [duplicate]

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 7 years ago.
I have the following code which works fine:-
$.getJSON("shipping.json")
.done(function(data) {
getUniqueCountries = function() {
var countries = [];
$.each(data.Services.intl.en, function( i, item ) {
if (countries.length==0) {
countries += item.countries;
}
else
{
countries += "," + item.countries;
}
});
}
})
However, I would like to make the first part of the $.each dynamic as this could be one of 3 possibilities based on a predefined variable, e.g.
var foo = "intl"
so the new line would read:-
$.each(data.Services.foo.en, function( i, item )
I can add another line of code and use an eval which works fine, but understand that this is not seen as best practice. i.e.
var foo = "intl";
var bar = eval("data.Services." + foo + ".en");
$.each(bar, function( i, item )
I have tried using JSON.parse (as seems to be popular way to resolve on google) instead of eval, i.e.
var bar = JSON.parse("data.Services." + foo + ".en");
but get an error :
'Unexpected token d'.
A snippet of the JSON file if needed :-
{
"Services": {
"intl": {
"en": [
{
"service": "PREMIER",
"countries": "United Kingdom",
"date": "Thursday 24th 10:00"
}
]
}
}
}
So I would like to know how to pass the variable foo into JavaScript to get the correct data and not get an error, without using the Eval function, or am I good to use the Eval function after all?
Thanks in advance for any help
If i'm understanding correctly, you should be able to do the following:
$.each(data.Services[foo].en, function( i, item ) {
if (countries.length==0) {
countries += item.countries;
}
else
{
countries += "," + item.countries;
}
});
Properties in javascript objects can be accessed as if you are accessing a particular key inside an array. For example you can do window.location or window["location"]
Hope this helps
It's actually fairly simple. JavaScript supports dynamic object keys with the [] notation:
data.Services[foo].en // Where foo = 'intl' or something.

reading json string in javascript [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 8 years ago.
I am trying to read a json string which looks like this.
"student":{
"0":[{
"name":"manet",
"marks":114
}],
"1":null,
"2":null,
"3":null,
"4":null,
"5":null,
"6":null,
"7":null,
"8":null,
"9":null,
"10":null,
"18":[{
"name":"Om",
"marks":75
}]
}
I am trying to read something like this
console.log("JSON Marks ", json[0].marks) or
console.log("JSON Marks #1", json[0][0].marks)
I just put jso[0] "0" is index i just put hardcoded to test
but none of the above is working
assuming that your code is saved in a variable called json then json.student[0][0].marks
You need this : http://jsbin.com/qazex/2/edit
console.log("JSON Marks ", json["student"][0][0].marks)
var json={"student":{
"0":[{
"name":"manet",
"marks":114
}],
"1":null,
"2":null,
"3":null,
"4":null,
"5":null,
"6":null,
"7":null,
"8":null,
"9":null,
"10":null,
"18":[{
"name":"Om",
"marks":75
}]
}};
console.log("JSON Marks ", json["student"][0][0].marks)
Try this way to access to object
var json = {"student":{
"0":[{
"name":"manet",
"marks":114
}],
"1":null,
"2":null,
"3":null,
"4":null,
"5":null,
"6":null,
"7":null,
"8":null,
"9":null,
"10":null,
"18":[{
"name":"Om",
"marks":75
}]
}
}
alert("JSON Marks "+ json["student"]["0"]["0"]["marks"]) ;
JSFIDDLE

How do I access CSV data using d3.js [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 9 years ago.
I have entered the following code in the Chrome console:
d3.csv("dataset32.txt")
.row(function(d) { return {time: +d.time, value: +d.val}; })
.get(function(error, rows) { console.log(rows); });
This returns an array of 160 objects which has the data of my CSV file.
How do I reference the data in these objects?
The "dataset32.txt" is CSV data which looks like this:
time,val
0,1.8988762857143
0.0625,0
0.125,-2.6204492857143
0.1875,-0.34179771428571
The console prints out the result of the above commands as follows:
[Object, Object, Object…]
[0 … 99]
0: Object
time: 0
value: 1.8988762857143
__proto__: Object
So how do I reference the data inside these objects: "time" and "value"?
Here's a straight forward method for importing your csv file using d3.
d3.csv("path to the csv", function(data, error) { }).
More info about csv.
Here's a function that's help you.
Step 1 : Importing your CSV file.
d3.csv("path to your csv file", function(data, error) {
// You're function goes in here.
})
Step 2 : Targeting your data.
// This can be done using the data variable assigned in the function.
data.forEach(function(d) {
// Function goes in here.
})
Step 3 : Targeting your columns.
// Suppose you have 2 columns namely time and val.
data.forEach(function(d) {
// You can target your columns using this fucntion.
// function(d) {return d.colname}
// Here I'm parsing your time and val col numbers to actual numbers after importing.
d.time = +d.time;
d.val = +d.val;
})
Documentation for d3.
Hope this helps.

Categories

Resources