javascript, how to iterate parsed json correctly - javascript

Hi I have a json response that I have to parse. I want to pull the data and insert it into inputs value (if it exists)
My json is like this:
{"id":4,"comb_name":"Monitor__C9cGTqnM7Trz","resolution":null,"attribute_val":3,"porte":4, "deleted_at":null,"created_at":"2017-11-13 10:10:25","updated_at":"2017-11-13 10:10:25"}
The code:
if(isset(jsobj)) {
var parsed = JSON.parse(jsobj);
console.log(parsed);
for (var property in parsed) {
if(parsed.hasOwnProperty(property)) {
var possible_input = '#pro_' + property;
if($(possible_input).length) {
var actual_input = $(possible_input);
actual_input.val(property);
}
}
}
}
It actually works, the only problem is that "property" are "attribute_val", not "3". What can I do to grab the value of the property?

Just use the property name to access the value
actual_input.val(parsed[property]);

Related

JavaScript selecting Object Arraylike?

The Problem is the following:
I have a JSON file that has objects with the following name: "item0": { ... }, "item1": { ... }, "item2": { ... }. But I can't access them when going through an if method.
What I've done so far:
$.getJSON('/assets/storage/items.json', function(data) {
jsonStringify = JSON.stringify(data);
jsonFile = JSON.parse(jsonStringify);
addItems();
});
var addItems = function() {
/* var declarations */
for (var i = 0; i < Object.keys(jsonFile).length; i++) {
path = 'jsonFile.item' + i;
name = path.name;
console.log(path.name);
console.log(path.type);
}
}
If I console.log path.name it returns undefined. But if I enter jsonFile.item0.name it returns the value. So how can I use the string path so that it's treated like an object, or is there an other way on how to name the json items.
As others stated 'jsonFile.item' + i is not retrieving anything from jsonFile: it is just a string.
Other issues:
It makes no sense to first stringify the data and then parse it again. That is moving back and forth to end up where you already were: data is the object you want to work with
Don't name your data jsonFile. It is an object, not JSON. JSON is text. But because of the above remark, you don't need this variable
Declare your variables with var, let or const, and avoid global variables.
Use the promise-like syntax ($.getJSON( ).then)
Iterate object properties without assuming they are called item0, item1,...
Suggested code:
$.getJSON('/assets/storage/items.json').then(function(data) {
for (const path in data) {
console.log(data[path].name, data[path].type);
}
});
What you want is to use object notation using a dynamic string value as a key instead of an object key. So, instead of using something like object.dynamicName you either have use object[dynamicName].
So in your example it would be like this.
path = 'item' + i;
jsonFile[path].name
I'm afraid you cannot expect a string to behave like an object.
What you can do is this:
path = `item${i}`
name = jsonFile[path].name

Javascript: How to parse a json array without knowing the key name?

I want to parse the following json:
{"key_410441":{"hashId":"hash123","tube_id":"4accdefk31"}}
Where key_410441 is the entry's name representing the object's value, and the following array is the object's data.
How can I retrieve it's value?
function defined(json) {
for (var i in json) {
var objId = json[i]. ????
}
}
Like Robo Robok said, use Object.keys(object)
if your json look like {"key_410441":{"hashId":"hash123","tube_id":"4accdefk31"}}
function defined(json) {
var hashId = json[Object.keys(json)[0]].hashId
var tube_id = json[Object.keys(json)[0]].tube_id
}
}
you can use shortcut json[Object.keys(json)] because you have olny one object
key_410441
Object keys are returned in form of an array by Object.keys(object)
I suppose you are using jquery and ajax to get a json from an external file. Then the piece of code would be:-
$.getJSON("aa.json", function(data) {
var obj = Object.keys(data),
json = data[obj];
for(var s in json) {
console.log(json[s]);
}
});

Store values in javascript object with same keys

I have the following code to extract values from a JSON response. What I am trying to do is store the data in a similar way to how you would with an associative array in php. Apologies for the code being inefficient. The array comments written down are how I would like it to look in the object.
$.each(responseData, function(k1,v1){
if(k1 == "0"){
$.each(v1, function(k2,v2){
$.each(v2, function(k3, v3){
if(k3 == "val"){
//store in object here
//Array1 = array("time"=>k2, "iVal"=>v3)
console.log(k3 + v3 + k2);
}else{
//Array2 = array("time"=>k2, "aVal"=>v3)
console.log(k3 + v3 + k2);
}
});
});
}
});
So all the information is there but I am not sure how to store each instance for the values in an object. I did try store it like this:
//obj created outside
obj1.date = k2;
obj2.iVal = v3;
But doing this clearly overwrote every time, and only kept the last instance so I am wondering how can I do it so that all values will be stored?
Edit: Added input and output desired.
Input
{"0":{"18.00":{"iVal":85.27,"aVal":0.24},"19.00":{"iVal":85.27,"aVal":0.36},"20.00":{"iVal":0,"aVal":0}}, "success":true}
Desired output
array1 = {"time":"18.00", "iVal":85.27},{"time":"19.00", "iVal":85.27},{"time":"20.00", "iVal":0}
array2 = {"time":"18.00", "aVal":0.24},{"time":"19.00", "aVal":0.36},{"time":"20.00", "aVal":0}
try this :
var g1=[];
var g2=[];
for ( a in o[0])
{
g1.push({time:a , iVal:o[0][a]['iVal']})
g2.push({time:a , aVal:o[0][a]['aVal']})
}
http://jsbin.com/qividoti/3/edit
a json response can be converted back to a js object literal by calling JSON.parse(jsonString) inside the success callback of your ajax call.
from then on there is no need for iterating over that object since you navigate it like any other js object which is can be done in two ways either
the js way -> dot notation
var obj = JSON.parse(jsonStirng);
var value = obj.value;
or like a php array
var value = obj["value"];

Using string variable as a json object name

I have a dynamic string variable created by UI (valkey in below code) and I want to use that variable as a JSON key to get a value from TestObj which is a JSON object. But an attempt with the following code has returned an error.
var valkey=$('#cityfrm').val()+"_TO_"+$('#cityto').val();
if($('#cityfrm').val()!="NIL" || $('#cityto').val()!="NIL")
{
$.each(TestObj.valkey, function() {
var durn=this.duration;
var prc=this.price;
var curlegs=this.legs;
// updating ui
});
}
I appreciate any help.
TestObj.valkey will look for the key valkey in TestObj, which is undefined in your case that is why you are getting the error.
If you want to look for a key from a variable you need to use the syntax TestObj[valkey].
Ex:
var valkey=$('#cityfrm').val()+"_TO_"+$('#cityto').val();
if($('#cityfrm').val()!="NIL" || $('#cityto').val()!="NIL") {
$.each(TestObj[valkey], function() {
var durn=this.duration;
var prc=this.price;
var curlegs=this.legs;
// updating ui
});
}

Dynamically assigning object keys and values with "for"

I have a function, SWFUpload_config, which takes an argument, post_params_arr - an object.
post_params_arr = {"ajaxtask":"swfupload_files", "param": "2012"}
I need to parse that post_params_arr and dynamically add keys and values to swfu_settings in the following way (please notice that swfu_settings has by default 'SWFSESSID' : session_id and all other keys:values must be added from post_params_arr):
function SWFUpload_config (post_params_arr) {
var swfu_settings = {
'SWFSESSID' : session_id,
'ajaxtask' : 'swfupload_files',
'param' : '2012'
};
}
How can I achieve that? How would I parse post_params_arr inside swfu_settings where I am assigning keys and values?
The same way you'd access any other object...
var swfu_settings = {
ajaxtask: post_params_arr.ajaxtask,
param: post_params_arr.param
};
Or do you mean it's JSON? If you have jQuery, parse it using jQuery.parseJSON; otherwise, use JSON.parse and fall back on eval('(' + post_params_arr + ')').
If you need to shallow-clone the object for some reason, a for in loop will work:
var swfu_settings = {
SWFSESSID: 'blah'
// etc.
};
for(var x in post_params_arr) {
if(post_params_arr.hasOwnProperty(x)) {
swfu_settings[x] = post_params_arr[x];
}
}

Categories