This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 8 years ago.
I have a JSON string that looks like this:
[
{
"id": "acbPreviewCell",
"width": 80
},
{
"id": "advName",
"width": 170
},
{
"id": "adHeadline",
"width": 150
},
{
"id": "adSize",
"width": 150
},
{
"id": "adProduct",
"width": 150
},
{
"id": "adCategory",
"width": 150
},
{
"id": "adSection",
"width": 150
},
{
"id": "adColor",
"width": 150
},
{
"id": "adTags",
"width": 150
},
{
"id": "adRegions",
"width": 150
},
{
"id": "adStatus",
"width": 150
},
{
"id": "adCreated",
"width": 150
},
{
"id": "adBookingNb",
"width": 150
},
{
"id": "adPickup",
"width": 150
},
{
"id": "folioMeta",
"width": 150
}
]
To help explain further, each of these entries is the ID of a table header, along with the width of that table header. I'm using it within an application so that I can remember a user's custom column width that they set.
I would like to break this JSON string down into a javascript array, so that I can easily access each ID and it's width.
Any help would be appreciated with setting it up as an array and then breaking it down to access the ID and the width. Thank you!
If you want to convert it to an array you can use the built-in JSON object to parse it: JSON.parse(yourString).
But if you want to easily access values by ID, you will have to actually convert it to an object:
var originalData = JSON.parse(yourString);
var parsedData = {};
for (var i = 0, l = originalData.length; i < l; i++) {
parsedData[originalData[i].id] = originalData[i].width;
}
// now you can easily access the wanted widths
var acbPreviewCellWidth = parsedData['acbPreviewCellWidth'];
Someone else mentioned a hashed map, which is pretty much what I'm guessing you need. That is to say, you want to access by id quickly as in array['advName'] gives you the width there.
You could mill through the values you get like so:
a = [
{
"id": "acbPreviewCell",
"width": 80
},
{
"id": "advName",
"width": 170
},
{
"id": "adHeadline",
"width": 150
}
];
function rewrite_array(arr){
new_arr = new Array();
for( i=0; i<a.length; i++){
new_arr[arr[i]['id']] = arr[i]['width'];
}
return new_arr;
}
n = rewrite_array(a);
console.log(n["advName"]);
console.log(a[1]['width']);
In theory, it already is stored as an array. However, if you would like to parse the JSON object to ensure that it is properly formed, use var jsonArray = JSON.parse(jsonString); No jQuery is needed.
Use jQuery.parseJSON(jsonString)
You might want to get the JSON using ajax, and then loop through all the values lushing them to an array in javascript, or you can simply call var objArr = $.parseJSON('file'); to get an array of all the objects. If you want to fet the values, you van simply get them using objArr[index].val.
Using this you can call, for instance, the first objects values like this.
var id = objArr[0].id;
var width = objArr[0].width;
Try
function filtered(v) {
return $.map(json, function(value) {
return value.id === v ? value : null
})[0];
};
usage
filtered("folioMeta"); // do stuff with "folioMeta" object within array
filtered("folioMeta").id // `"folioMeta"`
filtered("folioMeta").width // `150`
Related
I am trying to access JSON values. This is the JSON object:
{
"attrs": {
"width": 1728,
"height": 787,
"dragabble": true
},
"className": "Stage",
"children": [
{
"attrs": {},
"className": "Layer",
"children": [
{
"attrs": {
"stroke": "green",
"strokeWidth": "5",
"points": [
348,564.125
]
},
"className": "Line"
}
]
}
]
}
And I am trying to use these values, like points, here:
socket.on("canvas-data", function(data){
var interval = setInterval(function(){
if(isDrawing) return;
setIsDrawing(true);
clearInterval(interval);
var obj = JSON.parse(data);
setStageData(obj);
var layer = new Konva.Layer();
var lines = new Konva.Line(
{
stroke: stageData.stroke,
strokeWidth: stageData.strokeWidth,
points: stageData.points
})
layer.add(lines);
stageEl.current.add(layer);
}, 200)
})
data is the JSON string, I tried to parse data into obj, set my stageData to obj and then set the corresponding JSON attributes to the values like stroke, strokeWidth and points. This doesn't work however, they're undefined. How do I access them?
(I also tried skipping the step where I set my stageData to obj, and just use obj.stroke instead of stageData.stroke etc.)
You can just skip using setStageData() and use the parsed object directly if you wish, or just name the parsed object stageData by default.
In any case, when you have nested objects and values in an Object, you access them by using the correct index, in your case, it would look this way:
socket.on("canvas-data", function(data) {
var interval = setInterval(function() {
if (isDrawing) return;
setIsDrawing(true);
clearInterval(interval);
var stageData = JSON.parse(data);
var layer = new Konva.Layer();
var lines = new Konva.Line(
{
stroke: stageData.children[0].children[0].attrs.stroke,
strokeWidth: stageData.children[0].children[0].attrs.strokeWidth,
points: stageData.children[0].children[0].attrs.points
});
layer.add(lines);
stageEl.current.add(layer);
}, 200);
})
Doesn't look very nice, but it works. You can always use this app called JSON Path list, which shows you all the possible paths and their values in a JSON object.
I have a sample json data,which I need to add in to different collections in mongodb.But I dont want whole json data.For example,
jsondata=
{"widget": {
"debug": "on",
"window": {
"title": "Sample Konfabulator Widget",
"name": "main_window",
"width": 500,
"height": 500
},
"image": {
"src": "Images/Sun.png",
"name": "sun1",
"hOffset": 250,
},
"text": {
"data": "Click Here",
"size": 36,
"style": "bold",
}}
In this json I want window key in one collection,simillarly image key in another mongo collection.
So I was thinking if I can save that key value pair in one variable,then I can add that variable in to collection.For this I was trying for each
var jsondat=JSON.parse(jsondata);
for(var exKey in jsondat) {
console.log("entering");
var b=stringdata[exKey].image;
console.log(b);
}
But I was unable to get that image key data.Is this the right approach for this?can someone help me out in this.
My expected result would be:
In one variable,The value of window key should be saved in json format.
Simillarly image and text keyvalues in another variables.
Thanks.
Why aren't you fetching window and image simply from the object as key like:
var window= jsondata.widget.window;
var image = jsondata.widget.image;
and save them in mongo db
db.window.insert(window)
db.image.insert(image)
Tell me If I understand it right.
I don't see much problem.
var jsondat=JSON.parse(jsondata);
for(var exKey in jsondat.widget) {
console.log("entering");
console.log(exKey);
if(exKey === 'image'){
db.image.insert(jsondat.widget[exKey]);
}else if(exKey === 'window'){
db.window.insert(jsondat.widget[exKey]);
}
// or db.getCollection(exKey).insert(jsondat.widget[exKey]);
}
But I would also add that normalization is not desirable in MongoDB, you should use embedding more because you won't be able to join collections later on if you want to collate data. But that's a general idea, maybe in your requirement you want different collection.
You can do it in several ways.
Method#1
var arr = [];
for(var i in jsondata.widget){
if(typeof(jsondata.widget[i])==='object'){
arr.push(jsondata.widget[i]);
}
};
console.log(arr);
Method#2
You can use unserscore utility library to get in easy
var _=require('underscore');
var arr = [];
_.each(jsondata.widget,function(o){
if(typeof(o)==='object'){
arr.push(o);
}
});
console.log(arr);
Now you can access all the object by index
Output
[ { title: 'Sample Konfabulator Widget',
name: 'main_window',
width: 500,
height: 500 },
{ src: 'Images/Sun.png', name: 'sun1', hOffset: 250 },
{ data: 'Click Here', size: 36, style: 'bold' } ]
Method#3
Try to get separate value of each inner keys
var window= jsondata.widget.window;
var image= jsondata.widget.image;
var text= jsondata.widget.text;
Edit
var obj={
"json": {
"window": {
"title": "sample",
"name": "sam"
},
"image": {
"src": "Images/Sun.png",
"name": "sun1",
"hOffset": 250
}
}
}
console.log(obj.json.window)
result-> {title: "sample", name: "sam"}
I'm trying to create a JSON array to send it to my web service. This is how my json should look like:
[{
"tipus": 1,
"proveidor": 3,
"atributs": {
"atribut":{
"id": 1,
"valor": 8
},
"atribut":{
"id": 2,
"valor": 500
}
}
}]
So, I have two general values "tipus" and "proveidor" and multiple "atributs" each "atribut" is composed with "id" and "valor".
When I construct the json I get this instead of what I want:
[
2:{
"tipus": 1,
"proveidor": 3,
1:{
"id": 1,
"valor": 8
},
0:{
"id": 2,
"valor": 500
}
}]
This is how I'm building the json:
// For every founded in $scope.atrb i need to create an 'atribut' element into my json
$scope.a = [];
var key;
for(key in $scope.atrb){
var newField = {
"idatributs_actiu": $scope.atrb[key].idatributs_actiu,
"nomAtribut": $scope.atrb[key].nomAtribut,
"valor": $scope.atrb[key].valor,
"idActiu": $routeParams.idTipusActiu,
"value": "",
"ordre": $scope.atrb[key].ordre,
"idatributs_generics": $scope.atrb[key].idatributs_generics
};
$scope.a.push(newField);
}
$scope.f = $scope.a;
});
var generics = {
"nom": $scope.nom,
"tipus": $routeParams.idTipusActiu,
"proveidor": $scope.proveidor.id
};
$scope.a.push(generics);
It's my first project with angular and I'm not sure if I'm building the json appropriately, basically i use an array to build a json but I don't know how to nested it 'atribut' inside 'atributs'.
The main idea is to read the 'generics' atributes and then loop through 'atributs' and read all 'atribut' element getting the properties.
Regards
Like S4beR and Kevin B told me, I just need to do an JS array. This is in my controller:
var obj = { generics: g, atributs: $scope.a };
g: it's an object with the generic properties
$scope.a: this is an array with 'atribut' objects which contais all
the properties I need save to.
I really want to convert a object to array but my codes doesn’t worked.
data = "errors": {
"user": {
"name": "empty"
},
{
"length": "exceeds"
},
"title": {
"name": "empty"
},
{
"length": "exceeds"
}
}
Now I want to make them:
data = ["empty", "exceeds", "empty", "exceeds"];
What I’ve done so far is:
var arr = Object.keys(data[i].data.errors).map(function(k) {
return data[i].data.errors[k]
});
console.log(arr);
But the output is not what I expected. Please help. Thank very much.
If you always know the keys of the inner objects are going to be name and length a short way might be:
var out = Object.keys(data.errors).reduce(function (p, c) {
return p.concat([data.errors[c].name, data.errors[c].length]);
}, []);
DEMO
Given a JSON object such as this:
{
"something": {
"terms": [
{
"span": [
15,
16
],
"value": ":",
"label": "separator"
},
{
"span": [
16,
20
],
"value": "12.5",
"label": "number"
}
],
"span": [
15,
20
],
"weight": 0.005,
"value": ":12.5"
}
}
I asked a question about parsing the object out where label: number here:
JSON/Javascript: return which array object contains a certain property
I got a sufficient answer there (use filter()), but now need to know the original index of the object.
This issue seems to have the answer, but I simply don't know enough about javascript to translate it into something useful for my particular problem.
The following code successfully returns the object. Now I need to modify this to return the original index of the object:
var numberValue, list = parsed.something.terms.filter(function(a){
return a.label==='number';
});
numberValue = list.length ? list[0].value : -1;
This needs to be a pure javascript solution, no external libraries, etc.
I don't think you can modify the filter solution as within the filter you've lost the indexes.
The solution you've linked to uses the angular external library.
So here is a pure JS solution:
var numberValue = parsed.something.terms
.map(function(d){ return d['label']; })
.indexOf('number');
Array.prototype.indexOf()
Array.prototype.map()
Use forEach and collect the indices of objects that satisfy the a.label==='number' predicate :
var target = parsed.something.terms;
var list = [];
target.forEach(function(element, index){
if (element.label==='number') {
list.push(index)
};
});
var numberValue = list.length ? target[list[0]].value : -1;
console.log(list); // [1]
console.log(numberValue); // 12.5