I am trying to populate anchor links based on the ID in JSON data.
So far I have this JSON data.
{
"_meta": {
"status": "ok",
"api_version": 1,
"per_page": 20,
"current_page": 1,
"total_pages": 5,
"links": {
"next": "?page=2",
"previous": null
}
},
"data": [
{
"id": 1,
"name": "Andrew"
},
{
"id": 2,
"name": "Josh"
},
{
"id": 3,
"name": "John"
}
]
}
Here is my HTML code.
<div id = "links"></div>
Here is my jQuery code for fetching ids and displaying them on Anchor.
$.each(json.data, function(entryIndex, entry){
$("a.names").attr("href", "details?=" + entry.id);
$("#links").append('<a class = "names">View</a>');
console.log(entry.id);
});
What I'm trying to achieve here is to generate anchor links in , which would look like this on HTML.
View
View
View
Instead, the results were,
View
View
View
So, I debugged using console.log, which returned
1
2
3
How can I achieve this from getting ID of JSON and assign in Anchor Link?
This is not the way you do:
$("a.names").attr("href", "details?=" + entry.id);
So instead what you need to do is:
$("a.names").last().attr("href", "details?=" + entry.id);
The above will fetch the last one inserted. This is a dirty working fix.
In reality, you must do this way:
$.each(json.data, function(entryIndex, entry){
$("#links").append('<a class="names" href="details?=" + entry.id>View</a>');
console.log(entry.id);
});
Snippet
json = {
"_meta": {
"status": "ok",
"api_version": 1,
"per_page": 20,
"current_page": 1,
"total_pages": 5,
"links": {
"next": "?page=2",
"previous": null
}
},
"data": [
{
"id": 1,
"name": "Andrew"
},
{
"id": 2,
"name": "Josh"
},
{
"id": 3,
"name": "John"
}
]
}
$.each(json.data, function(entryIndex, entry){
$("#links").append('<a class="names" href="details?=" + entry.id>View</a>');
console.log(entry.id);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="links"></div>
Related
I am new to JSON and Postman. I believe I'm trying to do something very simple.
I have created a GET request which will get a JSON response like the one below.
In the example below I want to get the count of All "IsArchived" attributes in the response;
The number of those attributes will vary from response to response.
How can I do it? Thanks in advance
{
"Id": 1328,
"Name": "AAA Test",
"Owner": {
"Id": 208,
"Name": "The Boss"
},
"FieldGroups": [
{
"Id": "c81376f0-6ac3-4028-8d61-76a0f815dbf8",
"Name": "General",
"FieldDefinitions": [
{
"Id": 1,
"DisplayName": "Product Name",
"IsArchived": false
},
{
"Id": 2,
"DisplayName": "Short Description",
"IsArchived": false
},
{
"Id": 33,
"DisplayName": "Long Description",
"IsArchived": false
},
]
},
{
"Id": "5ed8746b-0fa8-4022-8216-ad3af17db91f",
"Name": "Somethingelse",
"FieldDefinitions": [
{
"Id": 123,
"DisplayName": "Attribution",
"IsArchived": false
},
{
"Id": 1584,
"DisplayName": "FC1",
"IsArchived": false
},
{
"Id": 623,
"DisplayName": "Sizes",
"IsArchived": false,
"Owner": {
"Id": 208,
"Name": "The Boss"
},
"Unit": "",
"Options": [
{
"Id": 1,
"Value": "XS"
},
{
"Id": 2,
"Value": "S"
},
{
"Id": 3,
"Value": "M"
}
]
}
]
}
],
"IsArchived": false
"Version": 1
}
It is a rather specific solution but I hope it helps. The description is added as comments:
// Convert the response body to a JSON object
var jsonData = pm.response.json()
// Create a count variable which will be increased by 1 everytime IsArchived occurs
var count = 0;
function countIsArchived() {
// Loop through the FieldGroupsArray
_.each(jsonData.FieldGroups, (fieldGroupsArray) => {
// Loop through the FieldDefinitionsArray
_.each(fieldGroupsArray.FieldDefinitions, (fieldDefinitionsArray) => {
// Check if IsArchived exists
if(fieldDefinitionsArray.IsArchived) {
// Increase count by 1
count++;
}
});
});
// IF you want it:
// Check if IsArchived exists on the top level of the JSON response and increase count
if(jsonData.IsArchived) {
count++;
}
// IF you want it:
// Create a Postman environment variable and assign the value of count to it
pm.environment.set("count", count);
}
Additional info:
The , after the following object is not needed. It invalidates the JSON:
{
"Id": 33,
"DisplayName": "Long Description",
"IsArchived": false
}, <--
I have Analysis Paralysis and need some input. I can modify the SQL query, the JavaScript, AND/or the CFML controller (all code has been posted below).
All I'm looking to do is to populate a select box with options and optgroups. The optgroup is what is tripping me up here.
The sql is pretty basic and looks like this:
SELECT
g.groupID,
g.groupLabel,
u.unitLabel,
u.unitID
FROM
group g
LEFT JOIN unit u ON g.groupID = u.groupID
And the CFML loop(s) is as follows (this is also where I believe the adjustment should be made with some logic such as if thisGroupLabel matches the preGroupLabel, stay within loop and keep adding unitLabel and unitIDs) but is there a more efficient way?:
local.data.unitLabels = [];
for(local.row in local.__unitLabels){
local.unit = {};
local.unit.groupLabel = local.row.groupLabel;
local.unit.unitLabel = local.row.unitLabel;
local.unit.unitID = local.row.unitID;
// loop over the array so that we can identify which one needs to be preselected
for(local.dataValue in local.data.unitDetails){
if (local.unit.unitID eq local.dataValue.unitID) {
local.unit.selected = 'selected';
} else {
local.unit.selected = '';
}
}
arrayAppend(local.data.unitLabels, local.unit);
}
The JSON data looks like this but I have access to the query so I can reformat it if needed:
{
"data": {
"selectDataOptions": [{
"groupLabel": "COMPLETION",
"selected": "",
"unitID": 1,
"unitLabel": "Completion"
}, {
"groupLabel": "DISTANCE",
"selected": "",
"unitID": 2,
"unitLabel": "Meters"
}, {
"groupLabel": "DISTANCE",
"selected": "",
"unitID": 3,
"unitLabel": "Miles"
}, {
"groupLabel": "DISTANCE",
"selected": "",
"unitID": 4,
"unitLabel": "Yards"
}, {
"groupLabel": "TIME",
"selected": "",
"unitID": 5,
"unitLabel": "Hours"
}, {
"groupLabel": "TIME",
"selected": "",
"unitID": 5,
"unitLabel": "minutes"
}, {
"groupLabel": "TIME",
"selected": "",
"unitID": 5,
"unitLabel": "Seconds"
}]
}
}
As it stands, my select box looks like this (roughly):
<select>
<optgroup>COMPLETION</optgroup>
<option>Complettion</option>
<optgroup>DISTANCE</OPTGROUP>
<option>Meters</option>
<optgroup>DISTANCE</optgroup>
<option>Miles</option>
<optgtroup>DISTANCE</optgroup>
<option>Yards</option>
<optgtroup>TIME</optgroup>
<option>Hours</option>
<optgtroup>TIME</optgroup>
<option>Minutes</option>
</select>
Notice that the optgroup Distance and TIME are repeated. The desired output would look like this:
<select>
<optgroup>COMPLETION</optgroup>
<option>Complettion</option>
<optgroup>DISTANCE</OPTGROUP>
<option>Meters</option>
<option>Miles</option>
<option>Yards</option>
<optgroup>TIME</optgroup>
<option>Hours</option>
<option>Mintues</option>
</select>
Is the issue how to construct a JSON string that Select2 can understand? I'd suggest creating a nested array of children for each GroupLabel, as described in the documentation under Grouped Data.
CF11+ and Lucee 4.5+ support cfloop "group", which would make things a lot easier. Just cfloop through the query and group by "groupLabel". (NB: Don't forget to modify the SQL query and ORDER BY g.groupLabel so the grouping works as expected.)
TryCF.com Example
Code:
data= [];
cfloop(query="qDemo", group="groupLabel") {
children = [];
cfloop() {
arrayAppend(children, {"id": qDemo.unitID, "text": qDemo.unitLabel});
}
arrayAppend(data, {"text" : qDemo.GroupLabel, "children" : children });
}
writeDump(serializeJSON(data));
Result:
[
{
"text": "COMPLETION",
"children": [
{
"text": "Completion",
"id": 1
}
]
},
{
"text": "DISTANCE",
"children": [
{
"text": "Meters",
"id": 2
},
{
"text": "Miles",
"id": 3
},
{
"text": "Yards",
"id": 4
}
]
},
{
"text": "TIME",
"children": [
{
"text": "Hours",
"id": 5
},
{
"text": "minutes",
"id": 5
},
{
"text": "Seconds",
"id": 5
}
]
}
]
I want jQuery to make new ul for each set of products.
Inside of each ul, all items of each set will be appended.
The result was unexpected; there should be only 2 ul, but
11 ul were appended.
My jQuery
$.getJSON('/products.json', function (result) {
var booksobj = result.ebooks.basic;
/* EBOOKS*/
$.each(booksobj.set, function(i, item) {
$('#ebook').append('<ul>'); // Append new list sets
$('#ebook ul').append('<li>' + item.title + '</li>');
});
});
products.json
{
"ebooks": {
"basic": {
"set": [
{
"title": "PDF Sample",
"product_id": 1,
"type": "ebook"
},
{
"title": "PDF Sample",
"product_id": 2,
"type": "ebook"
}, // ...
],
"set": [
{
"title": "PDF Sample",
"product_id": 1,
"type": "ebook"
},
{
"title": "PDF Sample",
"product_id": 2,
"type": "ebook"
}, // ...
]
}
}
}
Thanks in advance.
You're looping over set and for each item inside a set, you're creating a new ul element. You need to have multiple loops where you create an ul and afterwards add all the lis for the section. I changed your data structure, you don't need the set properties (and they're overriding each other as property names are unique). basic is now an array which consists of arrays which represent a set.
var data = {
"ebooks": {
"basic": [
[
{
"title": "PDF Sample 1",
"product_id": 1,
"type": "ebook"
},
{
"title": "PDF Sample 2",
"product_id": 2,
"type": "ebook"
},
],
[
{
"title": "PDF Sample 3",
"product_id": 1,
"type": "ebook"
},
{
"title": "PDF Sample 4",
"product_id": 2,
"type": "ebook"
},
]
]
}
}
data.ebooks.basic.forEach(function(set) {
var $list = $('<ul></ul>');
set.forEach(function(pdf) {
$list.append('<li>' + pdf.title + '</li>')
});
$('#ebook').append($list);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ebook"></div>
It looks like the problem stems from the selectors in this snippet:
$('#ebook').append('<ul>'); // Append new list sets
$('#ebook ul').append('<li>' + item.title + '</li>');
The selector "$('#ebook ul')" won't select the newly added ul in the iteration, instead it'll append to the first match (so the first ul added to the #ebook div). Instead, try chaining your calls like so:
/* EBOOKS*/
$.each(booksobj.set, function(i, item) {
$('#ebook').append('<ul>').append('<li>' + item.title + '</li>');
});
Working example with JSON data in a variable: http://codepen.io/JasonGraham/pen/WxbvRo
Your problem is use $('#ebook ul'), another question, why you use the key "set" two times? No make sense,
var data = {
"ebooks": {
"basic": [
[
{
"title": "PDF Sample 1",
"product_id": 1,
"type": "ebook"
},
{
"title": "PDF Sample 2",
"product_id": 2,
"type": "ebook"
},
],
[
{
"title": "PDF Sample 3",
"product_id": 1,
"type": "ebook"
},
{
"title": "PDF Sample 4",
"product_id": 2,
"type": "ebook"
},
]
]
}
}
$.each(data.ebooks.basic, function(i, item) {
$('#ebook').append('<ul>'); // Append new list sets
$.each(item, function(i, item2) {
$('#ebook ul:last').append('<li>' + item2.title + '</li>');
});
});
see the fiddle
I have a JSON response and I am trying to get autocomplete to work but it is having issues.
Question:
Here is my jQuery ajax "success" method to handle the returned JSON string: (I have listed my JSON response below):
The Code:
success: function( data ) {
response( $.map( data.productSkus, function( item ) {
return {
label: item.product.name + " - " + item.product.sku,
name: item.product.name,
value: item.product.sku,
id: item.product.id,
product_sku: item.product.sku
}
}));
}
The Issue:
I am sure that the issue why it isn't showing options is because each array element has the "0": { before the content of the array. How do I access these? I have tried item[0] but that does not seem to work. I know that this script works, it just broke when I had to do a "group by" in my php code. Once I did the group by it added the "0": {. Thanks for your help!
JSON Response:
{
"responseCode": 200,
"responseVal": "Success",
"productSkus": [
{
"0": {
"id": 16685,
"qty": 8,
"reserved_qty": 0,
"created": {
"date": "2014-01-20 17:32:31",
"timezone_type": 3,
"timezone": "Europe/Paris"
},
"updated": null,
"deletedAt": null,
"inventoryLocation": {
"id": 523,
"saleable": true,
"name": "M-10A-4",
"created": {
"date": "2013-04-11 18:46:11",
"timezone_type": 3,
"timezone": "Europe/Paris"
},
"updated": {
"date": "2013-04-11 18:46:11",
"timezone_type": 3,
"timezone": "Europe/Paris"
},
"deletedAt": null,
"warehouse": {
}
}
},
"name": "Tiger Costume Brown"
},
{
"0": {
"id": 48917,
"qty": 0,
"reserved_qty": 0,
"created": {
"date": "2014-01-20 23:44:15",
"timezone_type": 3,
"timezone": "Europe/Paris"
},
"updated": null,
"deletedAt": null,
"inventoryLocation": {
"id": 4056,
"saleable": true,
"name": "W-2E-26R-204",
"created": {
"date": "2014-01-20 23:30:58",
"timezone_type": 3,
"timezone": "Europe/Paris"
},
"updated": null,
"deletedAt": null,
"warehouse": {
}
}
},
"name": "Tiger Costume White"
}
],
"productsCount": 7
}
I would doublecheck this on the phpside and maybe correct it (just take the element under zero and append it directly). If this isnt possible correct it in JS:
success: function( data ) {
response( $.map( data.productSkus, function( item ) {
if(item[0]){
item[0].name = item.name
item = item[0];
}
return {
label: item.name + " - " + item.sku,
name: item.name,
value: item.sku, // Not in the JSON
id: item.id,
product_sku: item.sku // Not in the JSON
}
}));
}
When this isnt working, use typeof instead.
// Edit: Did crap. Corrected it
// Edit: Removed the product-key since it is not present in the JSON
// Edit: Now it nearly fits the json
My issue was actually in my PHP code. Disregard this question all together.
Basically I want to be able, in Javascript (JQuery optionally), to search into a JSON with nested elements for a particular element and edit it.
Ex. search for "components" with id 110 and change the name to "video card".
Notice the following JSON is just an example. I am wondering if javascript libraries or good tricks exist to do such a thing, I don't think traversing the whole json or writing my own methods is the best solution.
{
"computers": [
{
"id": 10,
"components": [
{
"id": 56,
"name": "processor"
},
{
"id": 24,
"name": "ram"
}
]
},
{
"id": 11,
"components": [
{
"id": 110,
"name": "graphic card"
},
{
"id": 322,
"name": "motherboard"
}
]
}
]
}
You could try linq.js.
You can use this javascript lib, DefiantJS (http://defiantjs.com), with which you can filter matches using XPath on JSON structures. To put it in JS code:
var data = {
"computers": [
{
"id": 10,
"components": [
{ "id": 56, "name": "processor" },
{ "id": 24, "name": "ram" }
]
},
{
"id": 11,
"components": [
{ "id": 110, "name": "graphic card" },
{ "id": 322, "name": "motherboard" }
]
}
]
},
res = JSON.search( data, '//components[id=110]' );
res[0].name = 'video card';
Here is a working fiddle;
http://jsfiddle.net/g8fZw/
DefiantJS extends the global object JSON with the method "search" and returns an array with matches (empty array if no matches were found). You can try out the lib and XPath queries using the XPath Evaluator here:
http://www.defiantjs.com/#xpath_evaluator