This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 3 years ago.
Suppose I have a JSON Object like this:
var data = {
"name": "abcd",
"age": 21,
"address": {
"streetAddress": "88 8nd Street",
"city": "New York"
},
"phoneNumber": [
{
"type": "home",
"number": "111 111-1111"
},
{
"type": "fax",
"number": "222 222-2222"
}
]
}
and I want to get the information from this json object by using path which is a string, like
var age = 'data/age'; // this path should return age
var cityPath = 'data/address/city'; // this path should return city
var faxNumber = 'data/phoneNumber/1/number'; // this path should return fax number
Is there any way I can get this information from the string path? Currently I am splitting the path by / and then using it like data.age or data.address.city. But this approach is not useful for any array contained in JSON object.
Is there any better and optimal approach in JavaScript for this problem?
This is how you can access the data from the JSON, no need to use paths:
var data = {
"name": "abcd",
"age": 21,
"address": {
"streetAddress": "88 8nd Street",
"city": "New York"
},
"phoneNumber": [
{
"type": "home",
"number": "111 111-1111"
},
{
"type": "fax",
"number": "222 222-2222"
}
]
}
var age = data.age;
var cityPath = data.address.city;
var faxNumber = data.phoneNumber[0].number; // array first item begins with 0
console.log({age, cityPath, faxNumber})
If you really need to use paths for some reason, I suggest using lodash get method https://lodash.com/docs#get
Related
{
"2": [{
"name": "Jeevan",
"age": "7"
},
{
"name": "Jeet",
"age": "8"
}],
"school": "Kendriya Vidyalaya"
}
I am having this JSON stored in variable named Obj. I would like to access individual JSON Objects inside of JSON Array which has a a key as "2".
Please help me to access the same.
As far as conventional way is considered i.e
Obj.key, it is not applicable here because Obj.2 or Obj."2" is not allowed.
I believe you are working with javascript.
Try to access the date like this:
array = Obj["2"]
This should work
var o = { "2": [{ "name": "Jeevan", "age": "7" }, { "name": "Jeet", "age": "8" } ], "school": "Kendriya Vidyalaya" };
o["2"];
o["school"]
This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 6 years ago.
I am working on an ionic 1 app, I do not know if there is a way but for example, here, is there a way I can dynamically assign a parent in this object depending on the value of the Variable?
var contact = {
"Name": "John Doe",
"available": true,
Variable: [
{
"Location": "Home",
"Number": "33"
},
{
"Location": "Work",
"Number": "22"
}
]
};
Lets say Variable = "friends" Then
var contact = {
"Name": "John Doe",
"available": true,
"Friends": [
{
"Location": "Home",
"Number": "33"
},
{
"Location": "Work",
"Number": "22"
}
]
};
I know I can use ES6, the Computed Property Names [Variable] but they are not working on older devices. Is there any alternative method?
Just plain old
var contact = {
"Name": "John Doe",
"available": true,
};
contact[Variable] = [
{
"Location": "Home",
"Number": "33"
},
{
"Location": "Work",
"Number": "22"
}
]
I want to create a simple application for managing contacts. I want to be able to add new contacts and delete contacts. So I'm thinking the best approach is to create a contacts constructor so as to be able to create contacts objects with it. I'm planing to use set and get methods with this constructor.
How do I create a contacts constructor with these value in it.
The contact information should be represented as JSON, for example:
{
"id": "0001",
"first_name": "Charles",
"last_name": "Bronson",
"year_of_birth": 1921,
"email": "charles#bronson.com",
"image_url": "http://image.toutlecine.com/photos/b/r/o/bronson-charles-01-g.jpg",
"addresses": {
"address": [
{ "id": "1001", "street_name": "Storgata", "city": "Åhus" },
{ "id": "1003", "street_name": "Lillgata", "city": "Åhus" },
]
},
"phones": [
{ "id": "5001", "type": "mobile", "number": "070112233" },
{ "id": "5002", "type": "home", "number": "046445566"
]
}
is this a correct way to create a constructor of this sort?
function contacts() {
this.id = id;
this.first_name = first_name;
this.last_name = last_name;
this.year_of_birth = year_of_birth;
this.email = email;
this.image_url = image_url;
this.adressess = adress["id", "street_name", "city"];
this.phones = phone["id", "type", "number"];
}
Thanks!!
You have an array of address objects within an addresses object:
addresses.address[0].id is the way to get the id of the first address object in that array.
addresses.address[1].id would get the id of the second address object
and so on...
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 some data like :
{
"_id": ObjectId("528ae48e31bac2f78431d0ca"),
"altitude": "110",
"description": [
{
"id": "2",
"des": "test"
}
],
"id": "1",
"latitude": "24.9528802429251",
"longitude": "121.509316013427",
"name": "H hotel"
}
i want get description length and show it context
please help me!!
You don't provide much information, but here's an overview. I'm assuming you have a JSON string and not an object yet. I shall call him, "Jason Data" ...or rather jsonData.
Something like this for illustrative purposes (only without the new lines since you can't do multi-line strings in JavaScript in this fashion, but you get the idea):
// Jason Data, head full of doubt, road full of promises
var jsonData = '{
"_id": "528ae48e31bac2f78431d0ca",
"altitude": "110",
"description": [
{
"id": "2",
"des": "test"
}
],
"id": "1",
"latitude": "24.9528802429251",
"longitude": "121.509316013427",
"name": "H hotel"
}';
And then treat our outpatient, Jason Data:
// let's get his Mona Lisa
var data = JSON.parse(jsonData);
// since he holds numerous memories, let's first get the count (as you wish)
var numDescriptions = data.description.length;
// as if we were psychiatrists, we will now analyze each of his experiences
for ( var i = 0; i < numDescriptions; i++ ) {
// and write a poem about his life. (even though this goes against doctor-patient privilege, sue me)
console.log(data.description[i].id,data.description[i].des);
}
This is a JSON data you can stringfy and parse that data.
var data = JSON.stringify({
"_id": "ObjectId(528ae48e31bac2f78431d0ca)",
"altitude": "110",
"description": [
{
"id": "2",
"des": "test"
}
],
"id": "1",
"latitude": "24.9528802429251",
"longitude": "121.509316013427",
"name": "H hotel"
})
var parseData = JSON.parse(data)
parseData.description.length
1
parseData.description[0].id
"2"
parseData.description[0].des
"test"
Suggestion: You can get the value of ObjectId(528ae48e31bac2f78431d0ca) outside this format, and pass that as String to _id value
First of all you need to validate your json,
{
"_id": "528ae48e31bac2f78431d0ca",
"altitude": "110",
"description": [
{
"id": "2",
"des": "test"
}
],
"id": "1",
"latitude": "24.9528802429251",
"longitude": "121.509316013427",
"name": "H hotel"
}
This is a valid json. Now you can do the desired like this -
$.getJSON('assets/json/demo.json', function(data) {
$.each(data, function(key, value){
if(key === 'description'){
var description_length = value.length;
}
});
});
And to display its content you can again loop over "description" some what like this -
$.each(value, function(index, val){
alert(index+'-'+val);
});
Your question is not clear, anyway if you are looking to get value corresponding to key "description" then try this yourdata.description to get it's value
I have created these steps at http://jsfiddle.net/twmSk/1/
//storing your data into variable yourdata
var yourdata = {
"_id": ObjectId("528ae48e31bac2f78431d0ca"),
"altitude": "110",
"description": [
{
"id": "2",
"des": "test"
}
],
"id": "1",
"latitude": "24.9528802429251",
"longitude": "121.509316013427",
"name": "H hotel"
}
$('#test').html(JSON.stringify(yourdata.description))
How could i parse this type of json data, getting in "results" to fetch single values like zipcode, state etc
{
"row": [
{
"id": "5",
"name": "test",
"email": "test#test.com",
"street": "mystreet",
"city": "mycity",
"state": "mystate",
"zipcode": "123456",
"myimage": "image.gif"}
]
}
first, you need to parse that string with JSON.parse
var myJson = JSON.parse(the_raw_data_string);
it ends up into an object like this:
var myJson = {
"row": [
{
"id": "5",
"name": "test",
"email": "test#test.com",
"street": "mystreet",
"city": "mycity",
"state": "mystate",
"zipcode": "123456",
"myimage": "image.gif"}
]
}
accessing the items:
myJson.row[0].id
myJson.row[0].name
myJson.row[0].street
//and so on...
you can take the json result to a var like follows
var json = {
"row": [
{
"id": "5",
"name": "test",
"email": "test#test.com",
"street": "mystreet",
"city": "mycity",
"state": "mystate",
"zipcode": "123456",
"myimage": "image.gif"}
]
}
then get the result to another
var result = json.row;
then you can iterate through the result
for (var i = 0; i < result.length; i++) {
var object = result[i];
for (property in object) {
var value = object[property];
alert(property + "=" + value); // This alerts "id=5", etc..
}
}
hope this will help you
Again here jQuery is your good friend
I have posted a sample using jsfiddle with multiple records in your data row
$(document).ready(function () {
var result = {
"row": [
{
"id": "5",
"name": "test",
"email": "test#test.com",
"street": "mystreet",
"city": "mycity",
"state": "mystate",
"zipcode": "123456",
"myimage": "image.gif"
},
{
"id": "10",
"name": "test2",
"email": "test2#test.com",
"street": "mystreet2",
"city": "mycity2",
"state": "mystate2",
"zipcode": "7891011",
"myimage": "image.gif"
}
]
};
var oE = $("#output");
$.each(result.row, function(index, value) {
//- extract target value like zipCode
oE.append($("<li></li>").text(value.zipcode));
});
});
Hope this helps.
If the json data is raw then use json.parse.
After that to loop the multi dimensional json data.
data = {"employees":[
{ "firstName":"Anushka", "lastName":"shetty" },
{ "firstName":"Shreya", "lastName":"Saran" },
{ "firstName":"Kajal", "lastName":"Agarwal" }
]};
for (var key in data.employees) {
alert(data.employees[key].firstName) //alert Anushka, Shreya, Kajal
}
You can use JQuery each function:
$.each(myData.row, function(index,item) {
// here you can extract the data
alert (item.zipcode);
});
Use JSON.parse(jsonstring). Then iterate over the objects/arrays.