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

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

Related

javascript, how to iterate parsed json correctly

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

When I am accessing the particular value in the array of JSON

Here is my array of JSON data. I want access the UserID field from array of JSON named as jsonResult.Please suggest me right solution for above JSON.
[
{
"UserRelationshipID":1,
"SubordinateUserID":1014,
"UserID":3,
"UserRelationshipTypeID":1
}
]
Your JSON Object
var jsonResult = [{
"UserRelationshipID":1,
"SubordinateUserID":1014,
"UserID":3,
"UserRelationshipTypeID":1
},{
"UserRelationshipID":2,
"SubordinateUserID":1015,
"UserID":4,
"UserRelationshipTypeID":1
}];
JavaScript
for(var i=0;i<jsonResult.length;i++){
console.log(jsonResult[i]); /*Access Object*/
console.log("User ID" + jsonResult[i].UserID); /*Access Only UserID*/
}
jQuery
$(jsonResult).each(function(Key,Value){
console.log(Value); /*Access Object*/
console.log(Value.UserID); /*Access Only UserID*/
});
Assuming you have array of objects, you can get the userid as shown below. Later you can either save the result in a variable or something else according to your need instead of consoling the result.
var jsonResult = [ {"UserRelationshipID":1,"SubordinateUserID":1014,"UserID":3,"UserRelationshipTyp‌​eID":1}, {"UserRelationshipID":1,"SubordinateUserID":2537,"UserID":3,"UserRelationshipTyp‌​eID":1}, {"UserRelationshipID":1,"SubordinateUserID":3,"UserID":4,"UserRelationshipTypeID‌​":1}, {"UserRelationshipID":1,"SubordinateUserID":7,"UserID":4,"UserRelationshipTypeID‌​":1}, {"UserRelationshipID":1,"SubordinateUserID":6,"UserID":2537,"UserRelationshipTyp‌​eID":1}, {"UserRelationshipID":1,"SubordinateUserID":3,"UserID":2537,"UserRelationshipTyp‌​eID":1}]
for(var i=0; i<jsonResult.length; i++){
console.log(jsonResult[i].UserID)
}
array().getJSONObject(0).get("UserID")
You have an array of objects and an object inside it. You intend to do something with the UserID ield of the object inside the array. You can do it like this:
yourarray[0].UserID
where yourarray is your JSON, 0 is the index of the very first object and UserID is the UserID member of that object. If you want to iterate your array and access UserID, then
for (var index in yourarray) {
//Do something with yourarray[index].UserID
}
More generally:
function iterateArray(arr, field) {
for (var index in arr) {
//Do something with arr[index][field]
}
}
and call it like this: iterateArray(yourarray, "UserID")

Trying to iterate over json string

I'm trying to iterate over this json encoded array which is a string:
"{"":{"count":{"total":112,"open":0,
"solved":0,
"deleted":106,
"closed":6},
"average_time_open_in_minutes":206,
"tickets_fortnight_week_count":11,
"tickets_last_week_count":15,"trend":1},
"Net2grid":{"count":"total":8,"open":0,"solved":0,"deleted":8},"average_time_open_in_minutes":0,"tickets_fortnight_week_count":0,"tickets_last_week_count":0,"trend":0},"Closed_by_merge":{"count":{"total":2,"open":0,"solved":0,"closed":2},"average_time_open_in_minutes":502,"tickets_fortnight_week_count":0,"tickets_last_week_count":0,"trend":0},"Analytics":{"count":{"total":1,"open":0,"solved":0,"deleted":1},"average_time_open_in_minutes":26,"tickets_fortnight_week_count":0,"tickets_last_week_count":0,"trend":0},"Meter":{"count":{"total":5,"open":5,"solved":0},"average_time_open_in_minutes":0,"tickets_fortnight_week_count":0,"tickets_last_week_count":2,"trend":1},"Installation":{"count":{"total":8,"open":5,"solved":3},"average_time_open_in_minutes":404,"tickets_fortnight_week_count":0,"tickets_last_week_count":0,"trend":0},"Other...":{"count":{"total":3,"open":2,"solved":1},"average_time_open_in_minutes":39,"tickets_fortnight_week_count":0,"tickets_last_week_count":0,"trend":0},"Meter Offline":{"count":{"total":8,"open":7,"solved":1},"average_time_open_in_minutes":8,"tickets_fortnight_week_count":0,"tickets_last_week_count":0,"trend":0},"App Usage":{"count":{"total":6,"open":5,"solved":0,"deleted":1},"average_time_open_in_minutes":8,"tickets_fortnight_week_count":0,"tickets_last_week_count":0,"trend":0}}"
An ajax call returns that string and i'm trying to only get the keys like: "app usage" and "Meter Offline" to return like so:
$.get('/ajax/ticket-and-notes-data.php', function (data) {
var problems = getProblems(data);
function getProblems(problems) {
var problemCategories = [];
$.each(JSON.parse(problems), function (key, value) {
if (key != "") {
problemCategories.push = key;
}
});
return problemCategories;
}
});
But I can't get the keys to go into the problemCategories.
I use this to set the categories in a highchart bubble chart and I will use more of the data from the string later.
I need to get this to work first.
The issue is in the way that you're using array.push. You should use array.push(item) instead of array.push = item.

How to get JSON object in array?

var data = '[{"type":"product","id":1,"label":"Size","placeholder":"Select Size","description":"","defaultValue"
:{"text":"Size30","price":"20"},"choices":[{"text":"Size30","price":"20","isSelected":"true"},{"text"
:"Size32","price":"22","isSelected":false},{"text":"Size34","price":"28","isSelected":false}],"conditionalLogic"
:""},{"type":"product","id":2,"label":"Color","placeholder":"Select Color","description":"","defaultValue"
:{"text":"Black","price":"10"},"choices":[{"text":"Black","price":"10","isSelected":"true"},{"text"
:"Green","price":"22","isSelected":false},{"text":"Red","price":"28","isSelected":false}],"conditionalLogic"
:""},{"type":"product","id":3,"label":"Rise","placeholder":"Select Rise","description":"","defaultValue"
:{"text":"Low","price":"8"},"choices":[{"text":"High","price":"12","isSelected":"true"},{"text"
:"Low","price":"8","isSelected":false}],"conditionalLogic"
:""}]';
Here I have posted my JSON data. I want to get all the defaultValue in JSON/Array format. My output should be like-
defaultValues:['Size30','Black','Low']
How to manage that in the foreach loop?
my code :
var otherSelectedOption;
angular.forEach(data, function(optionValue, optionKey) {
if (optionValue.defaultValue.text) {
otherSelectedOption = (optionValue.defaultValue.text);
}
selectedOption = {defaultValues: otherSelectedOption};
console.log(selectedOption);
});
Your JSON is not valid, since objects are not separated by comma ,
Suppose this is the JSON
var obj = '[{"type":"product","id":1,"label":"Size","placeholder":"Select Size","description":"","defaultValue"
:{"text":"Size30","price":"20"},"choices":[{"text":"Size30","price":"20","isSelected":"true"},{"text"
:"Size32","price":"22","isSelected":false},{"text":"Size34","price":"28","isSelected":false}],"conditionalLogic"
:""},{"type":"product","id":2,"label":"Color","placeholder":"Select Color","description":"","defaultValue"
:{"text":"Black","price":"10"},"choices":[{"text":"Black","price":"10","isSelected":"true"},{"text"
:"Green","price":"22","isSelected":false},{"text":"Red","price":"28","isSelected":false}],"conditionalLogic"
:""},{"type":"product","id":3,"label":"Rise","placeholder":"Select Rise","description":"","defaultValue"
:{"text":"Low","price":"8"},"choices":[{"text":"High","price":"12","isSelected":"true"},{"text"
:"Low","price":"8","isSelected":false}],"conditionalLogic"
:""}]';
try
var arr = JSON.parse(obj).map( function(item){
return item.defaultValue;
});

Converted JSON Array selection

So I made this code in Nodejs:
var stemidLength= JSON.memberList.members[0].length;
for (stemidIndex = 0; stemidIndex < stemidLength; stemidIndex++) {
var steamID64Length= JSON.memberList.members[steamidIndex].steamID64.length;
for (steamid64Index = 0; steamid64Index < steamid64Length; steamid64Index++) {
steam.addFriend(steamID64[i]);
}
}
And I'm trying to extract the steamid64s from the xml page here: http://steamcommunity.com/groups/Valve/memberslistxml/?xml=1.
I already converted the xml page into a JSON array.
What is wrong in my code? Getting error:
cannot read property 'members' of undefined.
EDIT: The JSON extracted array: http://pastebin.com/FECXEKMD
Thanks.
The JSON object is a built-in object for parsing JSON and converting strings to JSON. It does not have a memberList property.
I'll refer to the result of the XML to JSON conversion as steamUsers.
The IDs can be found in steamUsers.memberList.members[0].steamID64. You can add the IDs with the code below:
xmlToJson(urlxml, function(err, data) {
if (err) {
return console.err(err);
}
var steamUsers = data;
steamUsers.memberList.members[0].steamID64.forEach(function(memberID) {
steam.addFriend(memberID);
console.log(memberID);
});
});

Categories