I'm have a little trouble with some jQuery I have been trying to put together today.
Basically what I am trying to achieve is to dynamically have prices inserted into a price button on my page by reading from a JSON feed.
The idea is that there is an empty span that will contain the price. I have given all of the price spans the class .getPriceNew. Each span also has an id which is equal to the SKU number for the item like this <span class="getPriceNew" id="123456"></span>.
The mechanic is that for each span that has the class .getPriceNew the JSON will be queried for the information with the SKU id used as part of the query string.
Here is an example of the code i have tried
jQuery
$(".getPriceNew").each(function() {
var sku = $(this).attr("id");
var priceNew = $.getJSON('/api/MyApi.svc/GetProductBySku/'+sku , function(data) {
return(data.Variants[0].Price);
});
$(this).html("€"+priceNew);
})
HTML
<span class="getPriceNew" id="123456"></span>
<span class="getPriceNew" id="789123"></span>
<span class="getPriceNew" id="456789"></span>
<span class="getPriceNew" id="654321"></span>
JSON Example
This is what a single item from the JSON feed would look like - I have filtered it a little
/api/MyApi.svc/GetProductBySku/123456
Updated with valid JSON
{
"Age": {
"Description": "Age 18+",
"Thumbnail": "http://someurl.com/productImages/assets/img//icon18.gif"
},
"Barcode": {
"Barcode": "5026555408684"
},
"Description": "HTML",
"Id": 12214,
"Packshots": [
"http://someurl.com/productImages/914383/1min.jpg",
"http://someurl.com/productImages/914383/2med.jpg",
"http://someurl.com/productImages/914383/3max.jpg"
],
"Pegis": [],
"Platform": {
"Button": "Format",
"ID": 0
},
"Publisher": {
"Description": null
},
"Release": "/Date(1364252400000+0100)/",
"Screenshots": [],
"Title": "Product Title",
"Variants": [
{
"Id": 22488,
"MaxOrderQuantity": 3,
"Presellable": true,
"Price": 49.97,
"Sku": 914383,
"Type": {
"Description": "Pre-Order"
}
}
],
"Vendor": {
"Description": "Take Two Interactive Software"
},
"VideoHTML": "HTML",
"status": {
"Response": "product found",
"Success": true
}
}
I would love some help on this as I am really scratching my newbie head at this stage. I have managed to have console.log output the prices to the log but when I try and insert them back into the spans all I get is [object] [Object].
You are doing
$(".getPriceNew").each(function() {
var sku = $(this).attr("id");
var priceNew = $.getJSON('/api/MyApi.svc/GetProductBySku/'+sku , function(data) {
return(data.Variants[0].Price);
});
$(this).html("€"+priceNew);
})
getJSON returns a jqXHR object, which is not what you need. Try this:
$(".getPriceNew").each(function() {
var sku = $(this).attr("id");
// Save a refference to this span.
var thisSpan = $(this);
$.getJSON('/api/MyApi.svc/GetProductBySku/'+sku , function(data) {
// Request complete, NOW we can use the data we got!
thisSpan.html("€"+data.Variants[0].Price);
});
})
The callback is where you want to use the data you get from your AJAX calls. All AJAX methods ($.ajax, $.get, $.post, $.getJSON, etc) will return a jqXHR object.
I think your javascript code is correct but your Json output has two errors:
1: "Description":"Some HTML Description here, <- you forgot the closing quote
2: "ID":0}, <- delete the closing brace
So your Json will result like this:
{
"Age": {
"Description": "Age 18+",
"Thumbnail": "http://url.com/image.gif"
},
"Barcode": {
"Barcode": "4876416541647"
},
"Description": "Some HTML Description here",
"Id": 12214,
"Packshots": [
"http: //url.com/productImages/914383/1min.jpg",
"http: //http: //url.com/2med.jpg",
"http: //http: //url.com/3max.jpg"
],
"ID": 0,
"Publisher": {
"Description": null
},
"Release": "/Date(1364252400000+0100)/",
"Screenshots": [],
"Title": "Titleoftheproduct",
"Variants": [
{
"Id": 22488,
"MaxOrderQuantity": 3,
"Presellable": true,
"Price": 49.97,
"Sku": 914383,
"Type": {
"Description": "Pre-Order"
}
}
],
"Vendor": {
"Description": "Vendorname"
},
"VideoHTML": "<iframewidth="725"height="408"src="http: //www.youtube.com/embed/videoseries?list=PLofwA47XDv2_KnfUY52_8mlWg0iUEv8ci"frameborder="0"allowfullscreen></iframe>",
"status": {
"Response": "productfound",
"Success": true
} }
now your code
data.Variants[0].Price
will return 49.97
to validate Json you can paste it into http://jsonlint.com/ i think is very useful
Hope this helps
Related
thank you in advance for reading me. So I have been working in a filte. Right now my filter works, however doesn't do what I want. The current status is. When I select 2 options or more. I get all the values inside the data that contains either optionA oder optionB.
See my example data below:
{
"_uid": "1",
"body": [
{
"_uid": "2",
"name": "John",
"image": {
"id": 6807178,
"filename": "https://",
"copyright": "",
"fieldtype": "asset",
"is_external_url": false
},
"gewerk": "Project Owner",
"skill": ["vuejs", "react", "symfony"],
"component": "person",
},
{
"_uid": "3",
"name": "Jean",
"image": {
"id": 6807182,
"filename": "https://",
"copyright": "",
"fieldtype": "asset",
"is_external_url": false
},
"gewerk": "UI",
"skill": ["svelte"],
"component": "person",
},
{
"_uid": "4",
"name": "Martha",
"gewerk": "Frontend",
"skill": ["vuejs", "react"],
"component": "person",
},
{
"_uid": "5",
"name": "Tom",
"gewerk": "UI",
"skill": ["svelte", "angular", "vuejs"],
"component": "person",
}
],
}
With that being says when I filter using this example combi(screenshot). I get Martha, Tom and John as a result. When what I actually want is to have only Tom as a result. because only Tom have both criterias together inside his skills data.
This is my current computed function:
filterPersonSkill() {
return this.getComponentPerson.filter((e) =>
e.skill.map((skill) => this.multiValue.includes(skill)).includes(true)
);
}
At the beginning I used includes instead of map and that worked half. Because I was getting the result only if I selected in the same order(in the multiselect) as the array skills was appearing. Example below
filterPersonSkill() {
return this.getComponentPerson.filter((e) =>
e.skill.includes(...this.multiValue)
);
}
Thank in advance for the advice and reading me.
I think, it will be much simpler, if you add checkbox for the user to use "exact" filtering, i.e. results which include only selected tags.
With such a checkbox you can do something like this:
// your vue component
export default {
data() {
return {
exactMatch: true,
}
},
methods: {
filterPersonSkillExactMatch() {
const result = [];
for (const p of this.getComponentPerson) {
if (p.skill.length === this.multiValue.length
&& this.multiValue.every(val => p.skill.includes(val))) {
result.push(p)
}
}
return result
}
// somewhere in your code (either computed prop or method):
filteredPersons() {
if (exactMatch) {
return this.filterPersonSkillExactMatch()
}
return this.filterPerson()
}
}
}
Vijay Anand asked this question yesterday, but it was closed before he got an answer:
HTTP Response:
{
"entry": {
"#xml:base": "https://API_PROC_SRV/",
"#xmlns": "http://www.w3.org/2005/Atom",
"#xmlns:m": "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata",
"#xmlns:d": "http://schemas.microsoft.com/ado/2007/08/dataservices",
"id": "https://API_PROC_SRV/A_Order",
"title": {
"#type": "text",
"#text": "A_Order()"
},
"updated": "2020-02-29T07:33:28Z",
"category": {
"#term": "Type",
"#scheme": "http://schemas.microsoft.com/ado/2007/08/dataservices/scheme"
},
"link": [],
"content": {
"#type": "application/xml",
"m:properties": {
"d:Order": "123456789"
}
}
}
}
Javascript code:
var json = response;
var order = json.object.entry.content['m:properties']['d:Order']; // I intend to read Order no from the below response.
Error (example, jsbin.com):
"TypeError: Cannot read property 'entry' of undefined
at null.js:27:25
at https://static.jsbin.com/js/prod/runner-4.1.7.min.js:1:13924
at https://static.jsbin.com/js/prod/runner-4.1.7.min.js:1:10866"
Per JSLint, the response is valid JSON.
json.object.entry is obviously wrong ... but
Q: What is the correct Javascript syntax to access the "order" value (named d:Order), when m:properties and d:Order both have semicolons in the name?
PS: I nominated Vijay's original question for re-opening ... but I'm not optimistic. Hence my new question.
You need to parse the JSON. And there's no object property anywhere, it's jut json.entry.content.
response = `{
"entry": {
"#xml:base": "https://API_PROC_SRV/",
"#xmlns": "http://www.w3.org/2005/Atom",
"#xmlns:m": "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata",
"#xmlns:d": "http://schemas.microsoft.com/ado/2007/08/dataservices",
"id": "https://API_PROC_SRV/A_Order",
"title": {
"#type": "text",
"#text": "A_Order()"
},
"updated": "2020-02-29T07:33:28Z",
"category": {
"#term": "Type",
"#scheme": "http://schemas.microsoft.com/ado/2007/08/dataservices/scheme"
},
"link": [],
"content": {
"#type": "application/xml",
"m:properties": {
"d:Order": "123456789"
}
}
}
}`;
var json = JSON.parse(response);
var order = json.entry.content['m:properties']['d:Order'];
console.log(order);
Hi I'm currently creating an application to gather data form a website, and as I've researched you can used Json for that, now I have created a script to gather data, at first i have no problem with it, but when I cam across with a multi tree json i started having trouble.
here is my Json
{
"orders": [
{
"line_items": [
{
"id": 7660469767,
"name": "Personalised design - purple",
"properties": [
{
"name": "personalised text 1",
"value": "2"
},
{
"name": "personalised text 2",
"value": "Nuri &"
},
{
"name": "personalised text 3",
"value": "Samira"
}
],
}
]
}
]
}
I need to get the order.line_items.properties.value.
I tried this code but it says it does not work.
$.getJSON(order.json, function (data) {
$.each(data.orders.line_items.properties, function (index, value) {
$.each(this.value, function () {
console.log(this.text);
});
});
});
Can someone help me?
$.each(data.orders[0].line_items[0].properties, function (index, value) {
console.log(value.value);
});
Both orders and line_items are array, so it should have an access to array index first before accessing other object. And you don't have to use extra each in your code. The value above is an object for each properties. You can retrieve value there.
I wrote a quick script to parse two fairly large json file (~17k records) to do a comparison of the two. I have confirmed they are both valid json (via jsonlintpro) and the same format. (The source is the same so this should be a given. But, I always assume the mistake is mine. And I still do. Just somewhere else.) However, the parsed file just outputs [object, Object]. I'm wondering what the cause could possibly be?
The json format is like this small snippet (anonymized of course):
[
{
"id": "1234",
"name": "Name1",
"url": "https://localhost/Name1",
"date_created": "2013-07-05T18:47:05Z",
"date_cancelled": "",
"props": [
{
"id": "54321",
"type": "Client",
"value": "General Store"
},
{
"id": "65432",
"type": "Contact_Name",
"value": "Joe Smith"
}
]
},
{
"id": "23456",
"name": "Name2",
"url": "https://localhost/Name2",
"date_created": "2014-02-27T17:46:43Z",
"date_cancelled": "",
"props": [
{
"id": "34567",
"type": "Client",
"value": "Bait Shop"
}
]
}]
And here is the pertinent code:
var _ = require('underscore');
var recs = require('./prod.json');
printArr(recs);
console.log(recs.length);
function printArr(arr) {
arr.forEach(function(item) {
console.log(item + ", ");
});
}
Any guidance would be greatly appreciated.
UPDATE:
Ok, so apparently the issue is with my printArr function. I'm not sure what I'm doing wrong there. I'd like to figure it out because I want to expand upon that so I can print selectively.
the parsed file just outputs [object, Object].
This is the expected behavior BECAUSE you are concatenating an object with a string.
Try console.log(item) instead
console.log(item); should indeed print [object, Object], did you try to output its properties instead?
function printArr(arr) {
arr.forEach(function(item) {
console.log( item.id, item.name, item.url, item.date_created, item.date_cancelled, item.props, ';');
});
}
Just export the value from the prod.json file.
prod.json file
module.exports = [
{
"id": "1234",
"name": "Name1"
},
{
"id": "1234",
"name": "Name1"
}]
elsewhere
var recs = require('./prod.json')
console.log(recs)
I am getting a JSON in response from server:
{
"width": "765",
"height": "990",
"srcPath": "http://192.168.5.13:8888/ebook/user_content/_ADMIN_/_MERGED_/1273.pdf",
"coverPage": "",
"documents": [
{
"index": "1",
"text": "Archiving Microsoft® Office SharePoint® Server 2007 Data with the Hitachi Content Archive Platform and Hitachi Data Discovery for Microsoft SharePoint",
"type": "doc",
"id": "HDS_054227~201106290029",
"children": [
{
"text": "Page 1",
"leaf": "true",
"pageLocation": "http://192.168.5.13:8888/ebook/user_content/_ADMIN_/_IMAGES_/HDS_054227~201106290029/image_1.png"
},
{
"text": "Page 2",
"leaf": "true",
"pageLocation": "http://192.168.5.13:8888/ebook/user_content/_ADMIN_/_IMAGES_/HDS_054227~201106290029/image_2.png"
}
]
},
{
"index": "11",
"text": "Brocade FCoE Enabling Server I/O Consolidation",
"type": "doc",
"id": "HDS_053732~201105261741",
"children": [
{
"text": "Page 1",
"leaf": "true",
"pageLocation": "http://192.168.5.13:8888/ebook/user_content/_ADMIN_/_IMAGES_/HDS_053732~201105261741/image_1.png"
},
{
"text": "Page 2",
"leaf": "true",
"pageLocation": "http://192.168.5.13:8888/ebook/user_content/_ADMIN_/_IMAGES_/HDS_053732~201105261741/image_2.png"
}
]
}
]
}
And I want to get pagelocation of the children.
Can anyone tell me how to do this?
Hi
i also want to get indexes from this and then want to get pagelocations of that particular children. Can you tell me how would i do that?
And also when i when i am getting indexes array it is returning me ,, only and not the index nos.
I am using following code for that :
indexes=response.documents.map(function(e){ return e.children.index; })
Thanks & Regards
If you're interested in simply retrieving all the page locations, you can do it using filter:
var locations = [];
json.documents.forEach(function(e,i) {
e.children.forEach(function(e2,i2) {
locations.push(e2.pageLocation);
)}
});
// returns flat array like [item1,item2,item3,item4]
You can get an array of arrays using map:
var locations = [];
var locations = json.documents.map(function(e) {
return e.children.map(function(e2) {
return e2.pageLocation;
});
});
// returns 2-dimensional array like [[item1,item2],[item1,item2]]
Your json response is an appropriate javascript object So you can access all elements of the object like you do as in back end.
here, you have an array of object of the type documents and each document object has array of objects of the type children. so
syntax would be
myjson.documents[0].children[0].pagelocation
( = http://192.168.5.13:8888/ebook/user_content/_ADMIN_/_IMAGES_/HDS_054227~201106290029/image_1.png)
will give you the very first page location..
and so on