How Can I able to display following data is vue js? - javascript

My json response is
{"status": true, "data": {"basic": {"name": "haji", "dob": "2018-01-01", "gender": "male", "created_at": "2018-01-08T13:38:49.767Z", "firstname": "Ah", "lastname": "Sh", "userType": "Agent", "actor": 1, "username": "ashu", "contact": {"email": "ah#gmail.com", "phone": 863249517, "address": null}, "is_new": false, "is_email_verified": true, "is_phone_verified": true}, "wallet": {"amount": 144.0, "tds": 6.0}, "clan": null, "balance_lisitings": 48, "clan_status": false, "listings": [{"pid": 36, "name": "Labs", "website": "Labs", "category": {"name": "Education"}, "location": {"lat": 9.52766533190131, "lon":
76.8221354484558, "state": "Kerala", "country": "India", "district": {"id": 1, "name": "Kottayam"}, "city": {"id": 1, "name": "Kanjirappally"}, "place": {"id": 1, "name": "Koovappally"}}, "package": 0, "contact": {"email": "ah#gmail.com", "phone": 8986234851, "address": {"country": "India", "state": "Kerala", "name": "aloh", "pincode": 686895, "streetAddress": "Kottayam\nKanjirappally", "locality": "Koovappally", "city": "Koovappally"}}, "about": " IT company."}, {"pid": 37, "name": " Louis", "website": "ouis", "category": {"name": "Education"}, "location": {"lat": 10.0273434437709, "lon": 76.5288734436035, "state": "Kerala", "country": "India", "district": {"id": 1, "name": "Kottayam"}, "city": {"id": 1, "name": "Kanjirappally"}, "place": {"id": 1, "name": "Koovappally"}}, "package": 0, "contact": {"email": "soew988#gmail.com", "phone": 989756240, "address": {"country": "India", "state": "Kerala", "name": "allen45", "pincode": 686518, "streetAddress": "Sppally", "locality": "Koovappally", "city": "Koovappally"}}, "about": "fsdbgfnvb cvc"}], "total_listings": 2}}
========================================================================
My vue js script is
<script>
new Vue({
el: '#listings' ,
data: {
data: [],
},
mounted() {
this.$nextTick(function() {
var self = this;
$.ajax({
url: "https://",
method: "GET",
dataType: "JSON",
success: function (e) {
self.data = e.data;
},
});
})
},
})
</script>
My html code is
<div id="listings">
<h1>{{basic.name}}</h1>
<h2>{{basic.dob}}</h2>
like wise all data
</div>
Can anybody please help me to display the same. I am weak in js. This is the data I am getting I need to display the above data in vue js. I store all the data to a variable data[]. From it, how can I able to display the same?

One thing you'll need is a v-if to keep things from rendering when there's no data.
You have a data variable and basic is inside it. As you have it, all the things you want to include are inside it, so you will have a lot of things like data.basic.name.
const e = {
"status": true,
"data": {
"basic": {
"name": "haji",
"dob": "2018-01-01",
"gender": "male",
"created_at": "2018-01-08T13:38:49.767Z",
"firstname": "Ah",
"lastname": "Sh",
"userType": "Agent",
"actor": 1,
"username": "ashu",
"contact": {
"email": "ah#gmail.com",
"phone": 863249517,
"address": null
},
"is_new": false,
"is_email_verified": true,
"is_phone_verified": true
},
"wallet": {
"amount": 144.0,
"tds": 6.0
},
"clan": null,
"balance_lisitings": 48,
"clan_status": false,
"listings": [{
"pid": 36,
"name": "Labs",
"website": "Labs",
"category": {
"name": "Education"
},
"location": {
"lat": 9.52766533190131,
"lon": 76.8221354484558,
"state": "Kerala",
"country": "India",
"district": {
"id": 1,
"name": "Kottayam"
},
"city": {
"id": 1,
"name": "Kanjirappally"
},
"place": {
"id": 1,
"name": "Koovappally"
}
},
"package": 0,
"contact": {
"email": "ah#gmail.com",
"phone": 8986234851,
"address": {
"country": "India",
"state": "Kerala",
"name": "aloh",
"pincode": 686895,
"streetAddress": "Kottayam\nKanjirappally",
"locality": "Koovappally",
"city": "Koovappally"
}
},
"about": " IT company."
}, {
"pid": 37,
"name": " Louis",
"website": "ouis",
"category": {
"name": "Education"
},
"location": {
"lat": 10.0273434437709,
"lon": 76.5288734436035,
"state": "Kerala",
"country": "India",
"district": {
"id": 1,
"name": "Kottayam"
},
"city": {
"id": 1,
"name": "Kanjirappally"
},
"place": {
"id": 1,
"name": "Koovappally"
}
},
"package": 0,
"contact": {
"email": "soew988#gmail.com",
"phone": 989756240,
"address": {
"country": "India",
"state": "Kerala",
"name": "allen45",
"pincode": 686518,
"streetAddress": "Sppally",
"locality": "Koovappally",
"city": "Koovappally"
}
},
"about": "fsdbgfnvb cvc"
}],
"total_listings": 2
}
};
new Vue({
el: '#listings',
data: {
data: [],
},
mounted() {
const self = this;
self.data = e.data;
},
});
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<div id="listings" v-if="data.basic">
<h1>{{data.basic.name}}</h1>
<h2>{{data.basic.dob}}</h2>
like wise all data
</div>

Any data nested inside the data (and computed) property is available in the template between the {{ and }} tags.
For example:
Vue.element('my-element', {
template:
'<h1>This is an example!</h1>' +
'<h2>{{ msg }}</h2>'
data: function () {
return {
msg: 'default message'
}
},
So in your case, with nested properties it is exactly the same as you would access them in javascript:
Vue.element('my-element', {
template:
'<h1>This is an example!</h1>' +
'<h2>{{ data.wallet.amount }}</h2>'
'<h2 v-for="listing in listings" :key="listing.pid">{{ listing.name }}</h2>'
}
data: function () {
return {
data: []
}
},
Note
The data object should be returned from a function, from the original docs:
When defining a component, data must be declared as a function that returns the initial data object, because there will be many instances created using the same definition. If we use a plain object for data, that same object will be shared by reference across all instances created! By providing a data function, every time a new instance is created we can call it to return a fresh copy of the initial data. (https://v2.vuejs.org/v2/api/#data)
Further reading
I would advise you to read the Vue guide, especially the sections about
Declarative Rendering, Conditionals and Loops and Template Syntax
EDIT
While I was writing my answer, I see you edited your question.
Change your html to this:
<div id="listings">
<h1>{{data.basic.name}}</h1>
<h2>{{data.basic.dob}}</h2>
like wise all data
</div>

Related

accessing info from an API and displaying in h1

I have an API array I am practicing with. Below is one object from the array called users. I know in order to access the properties such as the firstName I simply write <h1> {users.firstName} </h1>. However, I am trying to display the address property within the "address" object. I thought it would be <h1> {users.address.address} </h1> but that isn't correct.
{
"id": 1,
"firstName": "Terry",
"lastName": "Medhurst",
"maidenName": "Smitham",
"age": 50,
"gender": "male",
"email": "atuny0#sohu.com",
"phone": "+63 791 675 8914",
"username": "atuny0",
"password": "9uQFF1Lh",
"birthDate": "2000-12-25",
"image": "https://robohash.org/hicveldicta.png",
"bloodGroup": "A−",
"height": 189,
"weight": 75.4,
"eyeColor": "Green",
"hair": {
"color": "Black",
"type": "Strands"
},
"domain": "slashdot.org",
"ip": "117.29.86.254",
"address": {
"address": "1745 T Street Southeast",
"city": "Washington",
"coordinates": {
"lat": 38.867033,
"lng": -76.979235
},
"postalCode": "20020",
"state": "DC"
},
"macAddress": "13:69:BA:56:A3:74",
"university": "Capitol University",
"bank": {
"cardExpire": "06/22",
"cardNumber": "50380955204220685",
"cardType": "maestro",
"currency": "Peso",
"iban": "NO17 0695 2754 967"
},
"company": {
"address": {
"address": "629 Debbie Drive",
"city": "Nashville",
"coordinates": {
"lat": 36.208114,
"lng": -86.58621199999999
},
"postalCode": "37076",
"state": "TN"
},
"department": "Marketing",
"name": "Blanda-O'Keefe",
"title": "Help Desk Operator"
},
"ein": "20-9487066",
"ssn": "661-64-2976",
"userAgent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/12.0.702.0 Safari/534.24"
}
You are most likely not looping over the array. To get the user's address, you need to get every object in the users array, then you can run .address.address on each of those objects. See the snippet below:
const users = [{
"id": 1,
"firstName": "Terry",
"lastName": "Medhurst",
"maidenName": "Smitham",
"age": 50,
"gender": "male",
"email": "atuny0#sohu.com",
"phone": "+63 791 675 8914",
"username": "atuny0",
"password": "9uQFF1Lh",
"birthDate": "2000-12-25",
"image": "https://robohash.org/hicveldicta.png",
"bloodGroup": "A−",
"height": 189,
"weight": 75.4,
"eyeColor": "Green",
"hair": {
"color": "Black",
"type": "Strands"
},
"domain": "slashdot.org",
"ip": "117.29.86.254",
"address": {
"address": "1745 T Street Southeast",
"city": "Washington",
"coordinates": {
"lat": 38.867033,
"lng": -76.979235
},
"postalCode": "20020",
"state": "DC"
},
"macAddress": "13:69:BA:56:A3:74",
"university": "Capitol University",
"bank": {
"cardExpire": "06/22",
"cardNumber": "50380955204220685",
"cardType": "maestro",
"currency": "Peso",
"iban": "NO17 0695 2754 967"
},
"company": {
"address": {
"address": "629 Debbie Drive",
"city": "Nashville",
"coordinates": {
"lat": 36.208114,
"lng": -86.58621199999999
},
"postalCode": "37076",
"state": "TN"
},
"department": "Marketing",
"name": "Blanda-O'Keefe",
"title": "Help Desk Operator"
},
"ein": "20-9487066",
"ssn": "661-64-2976",
"userAgent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/12.0.702.0 Safari/534.24"
}];
function App() {
return users.map(el => <h1>{el.address.address}</h1>);
}
// Render it
ReactDOM.render(<App /> , document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
It appears that you are attempting to access the usersobject.
Verify that it is an array by using the following code: const isUserArray = Array.isArray(users);
If the result is true, use a loop, such as users.map(user => <h1>{user.address.address}</h1>), to iterate through the array and access the address property of each user"

compare objects of same array and group their some properties when specific property matched with other object

I have an array of object as following :
"orders": [
{
"orderID": 1,
"fullName": "xyz",
"email": "xyz#gmail.com",
"phone": "12345",
"flatNo": "A-5",
"complex": "tara tra",
"landmark": null,
"street": null,
"area": "",
"city": "",
"productID": 2,
"name": "curd",
"price": 52,
"image": "curd.png",
"quantity": 1
},
{
"orderID": 1,
"fullName": "xyz",
"email": "xyz#gmail.com",
"phone": "12345",
"flatNo": "A-5",
"complex": "tara tra",
"landmark": null,
"street": null,
"area": "",
"city": "",
"productID": 1,
"name": "lassi",
"price": 65,
"image": "images\\rtoRAOwj4-conn.PNG",
"quantity": 1
},
{
"orderID": 2,
"fullName": "velocity",
"email": "velocity#gmail.com",
"phone": "999999",
"flatNo": "b-863",
"complex": "tara tra",
"landmark": "kaskd",
"street": "asdasd",
"area": "rob city",
"city": "asda",
"productID": 1,
"name": "lassi",
"price": 65,
"image": "images\\rtoRAOwj4-conn.PNG",
"quantity": 3
}
]
Here if the orderID is same for the object I want to merge those object into a single object and create the product information into an array of an object within the main array
Here is the output which I am looking for
"orders": [
{
"orderID": 1,
"fullName": "xyz",
"email": "xyz#gmail.com",
"phone": "12345",
"flatNo": "A-5",
"complex": "tara tra",
"landmark": null,
"street": null,
"area": "",
"city": "",
"products": [
{
"productID": 2,
"name": "curd",
"price": 52,
"image": "curd.png",
"quantity": 1
},
{
"productID": 1,
"name": "lassi",
"price": 65,
"image": "images\\rtoRAOwj4-conn.PNG",
"quantity": 1
}
]
},
{
"orderID": 2,
"fullName": "velocity",
"email": "velocity#gmail.com",
"phone": "999999",
"flatNo": "b-863",
"complex": "tara tra",
"landmark": "kaskd",
"street": "asdasd",
"area": "rob city",
"city": "asda",
"productID": 1,
"name": "lassi",
"price": 65,
"image": "images\\rtoRAOwj4-conn.PNG",
"quantity": 3
}
]
basically I want to combine product information if the order ID is the same.
You'll have an easy time if you use my library for this.
const data = { orders: [ { "orderID": 1, "fullName": "xyz", "email": "xyz#gmail.com", "phone": "12345", "flatNo": "A-5", "complex": "tara tra", "landmark": null, "street": null, "area": "", "city": "", "productID": 2, "name": "curd", "price": 52, "image": "curd.png", "quantity": 1 }, { "orderID": 1, "fullName": "xyz", "email": "xyz#gmail.com", "phone": "12345", "flatNo": "A-5", "complex": "tara tra", "landmark": null, "street": null, "area": "", "city": "", "productID": 1, "name": "lassi", "price": 65, "image": "images\\rtoRAOwj4-conn.PNG", "quantity": 1 }, { "orderID": 2, "fullName": "velocity", "email": "velocity#gmail.com", "phone": "999999", "flatNo": "b-863", "complex": "tara tra", "landmark": "kaskd", "street": "asdasd", "area": "rob city", "city": "asda", "productID": 1, "name": "lassi", "price": 65, "image": "images\\rtoRAOwj4-conn.PNG", "quantity": 3 } ] }
const { pipe, assign, reduce, get, pick, omit } = rubico
const productKeys = ['productID', 'name', 'price', 'image', 'quantity']
const addOrderToMap = (m, order) => {
if (m.has(order.orderID)) {
m.get(order.orderID).products.push(pick(productKeys)(order))
} else {
m.set(order.orderID, {
...omit(productKeys)(order),
products: [pick(productKeys)(order)],
})
}
return m
}
const groupedByOrderID = assign({
orders: pipe([ // assign orders key
get('orders'), // data => orders
reduce(addOrderToMap, new Map()), // orders => Map { orderID -> orderWithProducts }
m => m.values(), // Map { orderID -> orderWithProducts } -> iterator { orderWithProducts }
Array.from, // iterator { orderWithProducts } -> [orderWithProducts]
]),
})(data)
console.log(groupedByOrderID)
<script src="https://unpkg.com/rubico/index.js"></script>
I've commented the code for you, here's the tour if you'd like to learn more.
Just in case if you want to do it through plain JavaScript you can make use of reduce:
var data=[ { "orderID": 1, "fullName": "xyz", "email": "xyz#gmail.com", "phone": "12345", "flatNo": "A-5", "complex": "tara tra", "landmark": null, "street": null, "area": "", "city": "", "productID": 2, "name": "curd", "price": 52, "image": "curd.png", "quantity": 1 }, { "orderID": 1, "fullName": "xyz", "email": "xyz#gmail.com", "phone": "12345", "flatNo": "A-5", "complex": "tara tra", "landmark": null, "street": null, "area": "", "city": "", "productID": 1, "name": "lassi", "price": 65, "image": "images\\rtoRAOwj4-conn.PNG", "quantity": 1 }, { "orderID": 2, "fullName": "velocity", "email": "velocity#gmail.com", "phone": "999999", "flatNo": "b-863", "complex": "tara tra", "landmark": "kaskd", "street": "asdasd", "area": "rob city", "city": "asda", "productID": 1, "name": "lassi", "price": 65, "image": "images\\rtoRAOwj4-conn.PNG", "quantity": 3 } ];
var result = Object.values(data.reduce((acc, {productID, name, price,image, quantity, ...rest})=>{
acc[rest.orderID] = acc[rest.orderID] || {...rest, products:[]};
acc[rest.orderID].products.push({productID, name, price,image, quantity});
return acc;
},{}));
console.log(result);

How can I access specific value of JSON object? [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 6 years ago.
I can't seem to console.log the item name and just that. It's in the position data -> pricing -> tables -> items -> name. I am going for an output that says "Toy Panda".
[
{
"event": "recipient_completed",
"data": {
"id": "msFYActMfJHqNTKH8YSvF1",
"name": "Sample Document",
"status": "document.draft",
"date_created": "2014-10-06T08:42:13.836022Z",
"date_modified": "2016-03-04T02:21:13.963750Z",
"action_date": "2016-09-02T22:26:52.227554",
"action_by": {
"id": "FyXaS4SlT2FY7uLPqKD9f2",
"email": "john#appleseed.com",
"first_name": "John",
"last_name": "Appleseed"
},
"created_by": {
"id": "FyXaS4SlT2FY7uLPqKD9f2",
"email": "john#appleseed.com",
"first_name": "John",
"last_name": "Appleseed",
"avatar": "https://pd-live-media.s3.amazonaws.com/users/FyXaS4SlT2FY7uLPqKD9f2/avatar.jpg"
},
"recipients": [
{
"id": "FyXaS4SlT2FY7uLPqKD9f2",
"email": "john#appleseed.com",
"first_name": "John",
"last_name": "Appleseed",
"role": "signer",
"recipient_type": "Signer",
"has_completed": true
}
],
"sent_by": {
"id": "FyXaS4SlT2FY7uLPqKD9f2",
"email": "john#appleseed.com",
"first_name": "John",
"last_name": "Appleseed",
"avatar": "https://pd-live-media.s3.amazonaws.com/users/FyXaS4SlT2FY7uLPqKD9f2/avatar.jpg"
},
"metadata": {
"salesforce_opp_id": "123456",
"my_favorite_pet": "Panda"
},
"tokens": [
{
"name": "Favorite Animal",
"value": "Panda"
}
],
"fields": [
{
"uuid": "YcLBNUKcx45UFxAK3NjLIH",
"name": "Textfield",
"title": "Favorite Animal",
"value": "Panda",
"assigned_to": {
"id": "FyXaS4SlT2FY7uLPqKD9f2",
"email": "john#appleseed.com",
"first_name": "John",
"last_name": "Appleseed",
"role": "Signer",
"recipient_type": "signer",
"has_completed": true,
"type": "recipient"
}
}
],
"pricing": {
"tables": [
{
"id": 82307036,
"name": "PricingTable1",
"is_included_in_total": true,
"summary": {
"discount": 10,
"tax": 0,
"total": 60,
"subtotal": 60
},
"items": [
{
"id": "4ElJ4FEsG4PHAVNPR5qoo9",
"qty": 1,
"name": "Toy Panda",
"cost": "25",
"price": "53",
"description": "Buy a Panda",
"custom_fields": {
"sampleField": "Sample Field"
},
"custom_columns": {
"sampleColumn": "Sample Column"
},
"discount": 10,
"subtotal": 60
}
],
"total": 60
}
]
},
"tags": [
"test tag",
"sales",
"support"
]
}
}
]
I would really appreciate a tip. Thank you
If you store your JSON object into variable called obj you can access that value ("Toy Panda") with:
obj.data.pricing.tables[0].items[0].name
because tables and items are arrays.
Here is a sample example :
<script>
var data = '{"name": "mkyong","age": 30,"address": {"streetAddress": "88 8nd Street","city": "New York"},"phoneNumber": [{"type": "home","number": "111 111-1111"},{"type": "fax","number": "222 222-2222"}]}';
var json = JSON.parse(data);
alert(json["name"]); //mkyong
alert(json.name); //mkyong
</script>
Refer this link :[https://www.mkyong.com/javascript/how-to-access-json-object-in-javascript/][1]
In your case it should be something like :
var data = // your json;
var json = JSON.parse(data);
console.log(json.pricing.tables.items[0].name;

ngRepeat:dupes error, although there is no duplication

I have a HTML code like below which I use AngularJS framework within it:
<select name="choose-staff" ng-model="admin_times[0].user" ng-change="update(reserve.staff)" id="choose-staff">
<option ng-repeat="value in staff | unique:'employee.user.username'" value="{[{ value.employee.user.username }]}">{[{ value.employee.user.first_name }]} {[{ value.employee.user.last_name }]}</option>
</select>
And I get an error like this:
Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: value in staff | unique:'employee.user.username', Duplicate key: string:ب, Duplicate value: ب
And if I use track by $index it destroys my desired structure and when I click one of options, the rest of them get vanished.
[
{
"employee": {
"user": {
"id": 3,
"first_name": "اشکان",
"last_name": "وکیلی",
"user_profile": null,
"username": "ashkan"
},
"business": {
"id": "caf241cd-adb4-44ee-8c40-0f6cdb3bc5ac",
"fa_name": "ساینا",
"en_name": "Saina",
"service": [],
"persian_address": "",
"location": "35.77885523664743,51.39051060551765",
"avatar": null,
"email": ""
},
"is_head": true
},
"service": {
"en_title": "Haircut",
"fa_title": "کوتاهی مو"
},
"allocated_time": 60,
"booked_no": "XG4OCX81"
},
{
"employee": {
"user": {
"id": 3,
"first_name": "اشکان",
"last_name": "وکیلی",
"user_profile": null,
"username": "ashkan"
},
"business": {
"id": "caf241cd-adb4-44ee-8c40-0f6cdb3bc5ac",
"fa_name": "ساینا",
"en_name": "Saina",
"service": [],
"persian_address": "",
"location": "35.77885523664743,51.39051060551765",
"avatar": null,
"email": ""
},
"is_head": true
},
"service": {
"en_title": "Color",
"fa_title": "رنگ مو"
},
"allocated_time": 25,
"booked_no": "1AY3F24G"
},
{
"employee": {
"user": {
"id": 2,
"first_name": "رضا",
"last_name": "ولیمرادی",
"user_profile": {
"id": "9d9be03a-f840-46ea-a21e-76cd5775a886",
"avatar": null,
"city": "",
"gender": "F",
"birthday": null,
"country": "IR",
"about": "",
"timestamp": "2015-11-06T14:56:10.312340Z",
"location": "36.03133177633187,51.328125"
},
"username": "reza"
},
"business": {
"id": "caf241cd-adb4-44ee-8c40-0f6cdb3bc5ac",
"fa_name": "ساینا",
"en_name": "Saina",
"service": [],
"persian_address": "",
"location": "35.77885523664743,51.39051060551765",
"avatar": null,
"email": ""
},
"is_head": false
},
"service": {
"en_title": "Yellow",
"fa_title": "زرد"
},
"allocated_time": 15,
"booked_no": "H989M93X"
},
{
"employee": {
"user": {
"id": 1,
"first_name": "علیرضا",
"last_name": "غفاری",
"user_profile": {
"id": "884b36e3-7bad-466f-afee-25801572b834",
"avatar": null,
"city": "",
"gender": "F",
"birthday": null,
"country": "IR",
"about": "",
"timestamp": "2015-11-06T14:56:39.522362Z",
"location": "32.24997445586331,53.26171875"
},
"username": "alireza"
},
"business": {
"id": "caf241cd-adb4-44ee-8c40-0f6cdb3bc5ac",
"fa_name": "ساینا",
"en_name": "Saina",
"service": [],
"persian_address": "",
"location": "35.77885523664743,51.39051060551765",
"avatar": null,
"email": ""
},
"is_head": true
},
"service": {
"en_title": "Color",
"fa_title": "رنگ مو"
},
"allocated_time": 20,
"booked_no": "O5KLFPZB"
}
]
I don't like the redundancy of employee.user.username
Looks to me like the unique value in each object is the booked_no.
In which case you should use track by value.booked_no

accessing Javascript object

may be a simple issue but cannot seem to solve it after some searching as well :) .. The scenario is as follows:
Using PhoneGap, am receiving a json object via Ajax using jquery. the object needs to be displayed on a next screen (first is the Search page and the next is the Search result page).
when the object is received, it is being saved in the sessionStorage variable (e.g. sessionStorage.result = data).
but when it is tried to be accessed on the next page, it gives an error saying that the property is unknown. e.g.
var result = sessionStorage.result;
alert(result.response.businesses[0].name);
have also tried:
alert($(result.response.businesses[0].name));
it says that the property is unknow. the basic structure of the json is as follows:
{
"action": "SearchBusiness",
"meta": {
"code": 200,
"message": "OK"
},
"response": {
"searchQuery": {
"categoryId": 4,
"communityId": 4,
"latitude": "",
"longitude": "",
"category": "Grocery Stores",
"community": "Indian/Pakistani",
"searchRadius": "",
"city": "",
"postalCode": ""
},
"businesses": [
{
"businessId": "2",
"name": "Name",
"address": "123",
"phone": "(123) 456 7890",
"city": "any city",
"country": "United States",
"state": "Abc",
"postalCode": "a123",
"url": "",
"logoUrl": null,
"latitude": "0.1951704",
"longitude": "-1.89512",
"categoryId": "4",
"communityId": "4",
"ratings": "0",
"ratingAvg": "0.00",
"distance": 0
}
]
Any help appreciated.
You are wrongly accessing that value,
Try,
var result = JSON.parse(sessionStorage.result);
alert($(result.businesses[0].name));
in your json codes missing } your codes must be like that
{
"action": "SearchBusiness",
"meta": {
"code": 200,
"message": "OK"
},
"response": {
"searchQuery": {
"categoryId": 4,
"communityId": 4,
"latitude": "",
"longitude": "",
"category": "Grocery Stores",
"community": "Indian/Pakistani",
"searchRadius": "",
"city": "",
"postalCode": ""
},
"businesses": [{
"businessId": "2",
"name": "Name",
"address": "123",
"phone": "(123) 456 7890",
"city": "any city",
"country": "United States",
"state": "Abc",
"postalCode": "a123",
"url": "",
"logoUrl": null,
"latitude": "0.1951704",
"longitude": "-1.89512",
"categoryId": "4",
"communityId": "4",
"ratings": "0",
"ratingAvg": "0.00",
"distance": 0
}]
}
}
alert(result.response.businesses[0].name); // it will work i think. no error
also look sessionstroge is there any data
Your Json string is not a valid JSON format plz check the format
{
"action": "SearchBusiness",
"meta": {
"code": 200,
"message": "OK"
},
"response": {
"searchQuery": {
"categoryId": 4,
"communityId": 4,
"latitude": "",
"longitude": "",
"category": "Grocery Stores",
"community": "Indian/Pakistani",
"searchRadius": "",
"city": "",
"postalCode": ""
},
"businesses": [{
"businessId": "2",
"name": "Name",
"address": "123",
"phone": "(123) 456 7890",
"city": "any city",
"country": "United States",
"state": "Abc",
"postalCode": "a123",
"url": "",
"logoUrl": null,
"latitude": "0.1951704",
"longitude": "-1.89512",
"categoryId": "4",
"communityId": "4",
"ratings": "0",
"ratingAvg": "0.00",
"distance": 0
}]
}
}

Categories

Resources