This question already has answers here:
Parse JSON in JavaScript? [duplicate]
(16 answers)
Closed 7 years ago.
I want to convert json to javascript array but its not working,
I tried the follwoing.
var arr = $.map(RatingGrade,function(value){ return value; });
var arr = Object.keys(RatingGrade).map(function(k) { return RatingGrade[k] });//not working on ie8
$.parse()
[{
"RGCode": 61,
"RGCode1": 61,
"ScoreMin": -1,
"ScoreMax": -1,
"GradeNo": "1+",
"GradeName": "Excellent",
"GradeDescription": "Excellent",
"createdby": 23,
"createdon": "/Date(1413970769020)/",
"updatedby": 23,
"updatedon": "/Date(1438628400000)/",
"status": "A",
"ScoreCardID": 1,
"PDLowerBound": 0,
"PDUpperBound": 0.03,
"MidPoint": 0.02,
"MaxPDMinPDDifference": 0.03,
"AveragePD": 0
}
]
how can i do this?also stringfy also but not working
What about?
JSON.parse('[{"RGCode": 61,"RGCode1": 61,"ScoreMin": -1,"ScoreMax": -1,"GradeNo": "1+","GradeName": "Excellent","GradeDescription": "Excellent","createdby": 23,"createdon": "/Date(1413970769020)/","updatedby": 23,"updatedon": "/Date(1438628400000)/","status": "A","ScoreCardID": 1,"PDLowerBound": 0,"PDUpperBound": 0.03,"MidPoint": 0.02, "MaxPDMinPDDifference": 0.03,"AveragePD": 0}]').forEach(function(item){
console.log(item);
});
This is an array. You just have to parse it.
Looks like map should do the job. Check the code and leave a comment if that does not work for you!
var data = {
"RGCode": 61,
"RGCode1": 61,
"ScoreMin": -1,
"ScoreMax": -1,
"GradeNo": "1+",
"GradeName": "Excellent",
"GradeDescription": "Excellent",
"createdby": 23,
"createdon": "/Date(1413970769020)/",
"updatedby": 23,
"updatedon": "/Date(1438628400000)/",
"status": "A",
"ScoreCardID": 1,
"PDLowerBound": 0,
"PDUpperBound": 0.03,
"MidPoint": 0.02,
"MaxPDMinPDDifference": 0.03,
"AveragePD": 0
}
var arr = Object.keys(data).map(function(T) {
return data[T]
});
console.log(arr);
Related
I am trying to update single value(ElementStatus) in below mentioned multidimentional JSON file.
BuildingID: 1521
BuildingName: "PEN LLOYD BUILDING"
BuildingNumber: "A"
ElementList: Array(15)
0: {ElementID: 114, SurveyTypeID: 3, Code: "M.01.01.01", ElementDescription: "M.01.01.01 Boilers/Plant", ElementStatus: "null"}
1: {ElementID: 115, SurveyTypeID: 3, Code: "M.01.01.02", ElementDescription: "M.01.01.02 Heat Emitters", ElementStatus: "null"}
2: {ElementID: 116, SurveyTypeID: 3, Code: "M.01.01.03", ElementDescription: "M.01.01.03 Distribution", ElementStatus: "completed"}
Here is the code
var newData=JSON.parse(success);
const data1 = newData[0].results.recordset[0].ElementList;
//console.log(data1.toArray());
var array=JSON.parse(data1)
array.forEach(function(element){
if(element.ElementDescription==elementsName)
{
element.ElementStatus="completed"
}
})
newData[0].results.recordset[0].ElementList=array
After iterating through forEach loop,I m getting ElementList in Array format.
But I want it in string format that is how it was earlier.
There are a number of problems with the code you show. The data you show is not in proper JSON format, so that will fail right off of the bat.
I have reworked your example to show proper input with JSON output.
let elementsName = "M.01.01.01 Boilers/Plant";
let success = `{"BuildingID": 1521,
"BuildingName": "PEN LLOYD BUILDING",
"BuildingNumber": "A",
"ElementList":
[{"ElementID": 114, "SurveyTypeID": 3, "Code": "M.01.01.01", "ElementDescription": "M.01.01.01 Boilers/Plant", "ElementStatus": null},
{"ElementID": 115, "SurveyTypeID": 3, "Code": "M.01.01.02", "ElementDescription": "M.01.01.02 Heat Emitters", "ElementStatus": null},
{"ElementID": 116, "SurveyTypeID": 3, "Code": "M.01.01.03", "ElementDescription": "M.01.01.03 Distribution", "ElementStatus": "completed"}]}`;
let newData=JSON.parse(success);
newData.ElementList.forEach(function(element){
if(element.ElementDescription==elementsName)
{
element.ElementStatus="completed"
}
});
let outputString = JSON.stringify(newData);
console.log(outputString);
This question already has answers here:
Find object by id in an array of JavaScript objects
(36 answers)
Closed 4 years ago.
I have an object in which I need to find a particular item index number. Below is my object:
[
{
"type": "Grayscale",
"mode": "average"
}, {
"type": "Sepia"
}, {
"type": "Invert",
"invert": true
}, {
"type": "Convolute",
"opaque": false,
"matrix": [1, 1, 1, 1, 0.7, -1, -1, -1, -1]
}, {
"type": "Convolute",
"opaque": false,
"matrix": [0, -1, 0, -1, 5, -1, 0, -1, 0]
}, {
"type": "Brownie"
}, {
"type": "Brightness",
"brightness": 0.35
}
]
For example, I need to find the index number of the item which has the value Invert for the type property. So in this case, the output should be 2. I only need to search the values of the type key.
You can use findIndex method, by passing a provided callback function as argument.
let arr = [ {"type":"Grayscale","mode":"average"}, {"type":"Sepia"}, {"type":"Invert","invert":true}, {"type":"Convolute","opaque":false,"matrix":[1,1,1,1,0.7,-1,-1,-1,-1]}, {"type":"Convolute","opaque":false,"matrix":[0,-1,0,-1,5,-1,0,-1,0]}, {"type":"Brownie"}, {"type":"Brightness","brightness":0.35} ], key = 'type';
console.log(arr.findIndex(elem => elem[key] == 'Invert'));
Here is a short snippet for the code.
var sample = [{"type":"Grayscale","mode":"average"},{"type":"Sepia"},{"type":"Invert","invert":true},{"type":"Convolute","opaque":false,"matrix":[1,1,1,1,0.7,-1,-1,-1,-1]},{"type":"Convolute","opaque":false,"matrix":[0,-1,0,-1,5,-1,0,-1,0]},{"type":"Brownie"},{"type":"Brightness","brightness":0.35}]
function findIndex(data, keyfield, value){
return data.indexOf(data.find(function(el,index){
return el[keyfield] === value;
}));
}
console.log(findIndex(sample, 'type', 'Invert'));
you can use underscore or loadash(_) package. It has multiple functionality support for array operations.
const _ = require('lodash')
let your_array= [
{"type":"Grayscale","mode":"average"},
{"type":"Sepia"},
{"type":"Invert","invert":true},
{"type":"Convolute","opaque":false,"matrix":[1,1,1,1,0.7,-1,-1,-1,-1]},
{"type":"Convolute","opaque":false,"matrix":[0,-1,0,-1,5,-1,0,-1,0]},
{"type":"Brownie"},
{"type":"Brightness","brightness":0.35}
];
let objectIndex = _.findIndex(your_array, each_element=> each_element.type == "Invert");
alert(objectIndex)
I know ton of library can prettyprint json just by indenting/newline stuff but here is a line of my heavy json:
"Shape6":{"bounds_start":[0,-6,0],"bounds_end":[3,1,3],"origin":[2,15,-1],"mirror":true,"rotation":[0,0,0.837758],"uv":[15,30]}
All the libraries i found output something like this:
"Shape6": {
"bounds_start": [
0,
-6,
0
],
"bounds_end": [
3,
1,
3
],
"origin": [
2,
15,
-1
],
"mirror": true,
"rotation": [
0,
0,
0.837758
],
"uv": [
15,
30
]
}
But i'm looking for a more human-readable way which not add new lines for small arrays that can fit in a line like:
"Shape6": {
"bounds_start": [0, -6, 0],
"bounds_end": [3, 1, 3],
"origin": [2, 15, -1],
"mirror": true,
"rotation": [0, 0, 0.837758],
"uv": [15, 30]
}
i do want this because my json file is like 6k+ lines on the first example
if you know a js or a php library (for ajax purposes)
i thank you in advance (and sorry for my poor english :))
you can simply do that with using JSON.stringify() function (see the reference https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify)
the first argument is the object you want to beautify, the second one is the function where we can specify the logic of line indention and new line breakings, the 3rd argument of this function (now 4) is the number for indention for your beautified JSON data
JSON.stringify(obj, function(k,v)
{
if (v instanceof Array)
return JSON.stringify(v);
return v;
}, 4);
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I am trying to create a JSON and populate it with some data. The data is a bit complex so I would like to have its "title", "name" and "value".
My issue is that I am not able to get the content from the JSON I created and getting "Uncaught SyntaxError: Unexpected token o" error message. However, if I just pass the json variable to console.log() I can see all the objects contained in the variable.
Please see the code below:
JSON
var json = [
{"title":"rice",
"value":{
"carb": 44.5,
"fat": 0.1,
"cal": 205,
"prot": 4.3
}
},
{"title":"buckwheat",
"value":{
"carb": 20,
"fat": 1,
"cal": 92,
"prot": 3
}
},
{"title":"potato",
"value":{
"carb": 50.5,
"fat": 0.5,
"cal": 225,
"prot": 5.9
},
}
]
JS
var obj = JSON.parse(json);
console.log(obj[0].title);
Maybe I don't understand your question but
JSON.parse()
As first parameter takes some String, text value, converts and returns it as JSON object. Since you have one - you can populate it with your data.
Your json data is not valid.
Valid Example
You can press f12 in Chrome or Mozilla and look console. You can find what is wrong with your JS code.
[
{
"title": "rice",
"value": {
"carb": 20,
"fat": 1,
"cal": 92,
"prot": 3
}
},
{
"title": "buckwheat",
"value": {
"carb": 20,
"fat": 1,
"cal": 92,
"prot": 3
}
},
{
"title": "potato",
"value": {
"carb": 50.5,
"fat": 0.5,
"cal": 225,
"prot": 5.9
}
}
]
Your var "json" is already a javascript object. Just add a semicolon to it and fix the one error (comma after "prot": 5.9}) :
var obj = [
{"title":"rice",
"value":{
"carb": 44.5,
"fat": 0.1,
"cal": 205,
"prot": 4.3
}
},
{"title":"buckwheat",
"value":{
"carb": 20,
"fat": 1,
"cal": 92,
"prot": 3
}
},
{"title":"potato",
"value":{
"carb": 50.5,
"fat": 0.5,
"cal": 225,
"prot": 5.9
}
} ];
You can simply get the values with:
console.log(obj[0].title);
If you want to parse json, save your data in string format.
I want to append following object array with existing one in angulajs for implementing load more feature.
ie,appending AJAX response with existing one each time.
I have one variable, $scope.actions which contains following JSON data,
{
"total": 13,
"per_page": 2,
"current_page": 1,
"last_page": 7,
"next_page_url": "http://invoice.local/activities/?page=2",
"prev_page_url": null,
"from": 1,
"to": 2,
"data": [
{
"id": 2108,
"action_type_id": 202,
"user_id": 1
},
{
"id": 2108,
"action_type_id": 202,
"user_id": 1
}
]
}
I want to append following JSON response each time this variable.
{
"data": [
{
"id": 2108,
"action_type_id": 202,
"user_id": 1
},
{
"id": 2108,
"action_type_id": 202,
"user_id": 1
}
]
}
I have tried with $scope.actions.data.concat(data.data);
but it is not working and getting following error message
$scope.actions.data.concat is not a function
You can use angular.extend(dest, src1, src2,...);
In your case it would be :
angular.extend($scope.actions.data, data);
See documentation here :
https://docs.angularjs.org/api/ng/function/angular.extend
Otherwise, if you only get new values from the server, you can do the following
for (var i=0; i<data.length; i++){
$scope.actions.data.push(data[i]);
}
This works for me :
$scope.array1 = $scope.array1.concat(array2)
In your case it would be :
$scope.actions.data = $scope.actions.data.concat(data)
$scope.actions.data.concat is not a function
same problem with me but i solve the problem by
$scope.actions.data = [].concat($scope.actions.data , data)
Simple
var a=[{a:4}], b=[{b:5}]
angular.merge(a,b) // [{a:4, b:5}]
Tested on angular 1.4.1