reading json string in javascript [duplicate] - javascript

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

Related

How to get D3 csv data into a different variable [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I am trying to extract imdb data from a csv and put two elements of it into an array of objects. There are 10 fields. I only want to use 2 in my chart. I am trying this:
var mydata;
// Grab the data
d3.csv('./movies.csv', function(csv){
csv.forEach(function(d){
mydata += {rating: d.imdbRating,
winsNoms: d.WinsNoms };
});
});
console.log(mydata);
Can somebody explain exactly what is going on here and why I get undefined when I try to output mydata in the final line? Finally, how do I change it around so it works?
You should push objects into an array. See adjustments below:
var mydata = [];
// Grab the data
d3.csv('./movies.csv', function(csv){
csv.forEach(function(d){
mydata.push({
rating: d.imdbRating,
winsNoms: d.WinsNoms
});
});
});
console.log(mydata);
You’ll need to first declare an empty array. Then you can push items into it.
To only use part of the set, you can use “slice” to truncate the array.
var mydata = [];
// Grab the data
d3.csv('./movies.csv', function(csv){
csv.forEach(function(d){
mydata.push({rating: d.imdbRating,
winsNoms: d.WinsNoms });
});
});
console.log(mydata);

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 open json file with objects in d3? [duplicate]

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]);
}
}

Replace one string with another using Angular.js or JavaScript [duplicate]

This question already has answers here:
Rename the property names and change the values of multiple objects
(3 answers)
Closed 7 years ago.
I have some JSON data and I need to replace one value with another string using Angular.js or JavaScript. My code is below:
$http({
method:'POST',
url:"php/getFilterCodeData.php",
data:filterData,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function successCallback(response){
console.log('filter',response.data);
$scope.last=[];
for(var i=0;i<response.data.length;i++){
$scope.arrCode=response.data[i].generated_code.split(',');
}
//console.log('arr',$scope.arrCode);
for(var i=0;i<$scope.arrCode.length;i++){
$scope.last.push($scope.arrCode[i].split("_").pop());
}
//console.log('last',$scope.last);
var newStr=$scope.last[0]+"-"+$scope.last[$scope.last.length-1];
//console.log('new str',newStr);
},function errorCallback(response) {
})
Here I am getting the below data using console:
filter [{
customer_name: "Big-Bazar"
expired_date: "23-12-2015"
generated_code: "medilink_global_01,medilink_global_02,medilink_global_03,medilink_global_04,medilink_global_05,medilink_global_06,medilink_global_07,medilink_global_08,medilink_global_09,medilink_global_10,medilink_global_11,medilink_global_12,medilink_global_13,medilink_global_14,medilink_global_15,medilink_global_16,medilink_global_17,medilink_global_18,medilink_global_19,medilink_global_20,medilink_global_21,medilink_global_22,medilink_global_23,medilink_global_24,medilink_global_25,medilink_global_26,medilink_global_27,medilink_global_28,medilink_global_29,medilink_global_30,medilink_global_31,medilink_global_32,medilink_global_33,medilink_global_34,medilink_global_35,medilink_global_36,medilink_global_37,medilink_global_38,medilink_global_39,medilink_global_40"
no_of_voucher: "40"
status: "generated"
voucher_amount: "3000"
voucher_code_id: "13"}]
Here I need to replace the generated_code: value with newStr. The expected output should be:
generated_code:01-40
In the Javascript:
$scope.filter = filter;
$scope.filter[0].generate_code = newStr;
To show the string, just use {{ filter[0].generate_code }} in your template.
AngularJS always watches changes to variables in the scope and will replace them in the template as they change, so it's pretty straight forward.
you do it like this:
response.data[i].generated_code=newStr;

Getting top 10 Values in a JSON File [duplicate]

This question already has answers here:
Sorting an array of objects by property values
(35 answers)
How to sort an array of objects with jquery or javascript [duplicate]
(6 answers)
Closed 8 years ago.
This is an example of my JSON file.
[
{"Variable":"Hello","Variable1":20}, {"Variable":"Hi","Variable1":30},
{"Variable":"How","Variable1":40}, {"Variable":"Who","Variable1":50},
{"Variable":"Where","Variable1":60}, {"Variable":"This","Variable1":100},
{"Variable":"Pork","Variable1":10}, {"Variable":"Creep","Variable1":90},
{"Variable":"Mega Creeps","Variable1":80}, {"Variable":"LOL","Variable1":0},
{"Variable":"ROFL","Variable1":0}, {"Variable":"LMAO","Variable1":0},
{"Variable":"POP","Variable1":0}, {"Variable":"LOVE","Variable1":0},
{"Variable":"PICK","Variable1":0}, {"Variable":"WHIZ","Variable1":0},
{"Variable":"BORED","Variable1":0}, {"Variable":"KILLAH","Variable1":0},
{"Variable":"LOLLING","Variable1":0}, {"Variable":"HALOO HALOO","Variable1":0}
]
How can I get only the Top 10 from highest Variable1 number to the least? But gonna be passing the JSON file as the same format.
First, parse the JSON into an array of Objects:
var data = JSON.parse(json);
Then combine sort and slice to achieve your goal:
var top10 = data.sort(function(a, b) { return a.Variable1 < b.Variable1 ? 1 : -1; })
.slice(0, 10);
See Array.sort
You can do it with Alasql JavaScript library. It download json file, parse it, and run
SQL statement on it. This is a sample how to take top 10 directly from JSON file:
<script src="alasql.min.js></script>
<script>
alasql("SELECT TOP 10 * FROM JSON('mydata.json') ORDER BY Variable1 DESC",[], function(top10){
console.log(top10);
});
</script>
Or if you already have data in memory:
var data = [{"Variable":"Hello","Variable1":20},{"Variable":"Hi","Variable1":30}];
var res = alasql("SELECT TOP 10 * FROM ? ORDER BY Variable1 DESC",[data]);
Try this sample in jsFiddle.

Categories

Resources