I'm trying to use the jQuery UI Autocomplete widget with a custom JSON feed I'm getting back from an API, which is formatted as follows:
{
"SearchTerm": "ches",
"HasDirectCountyHit": false,
"DirectCountyHitId": null,
"HasDirectLocationHit": false,
"DirectLocationHitId": null,
"Developments": [
{
"Id": "45339ae3e55a",
"Label": "Chestnut Walk, Bilston",
"Url": "/developments/chestnut-walk-bilston"
},
{
"Id": "4835f52e053a",
"Label": "Crown Park, Chester",
"Url": "/developments/crown-park-chester"
},
{
"Id": "757964964cc6",
"Label": "The Birches, West Timperley",
"Url": "/developments/the-birches-west-timperley"
}
],
"Counties": [
{
"Id": "7",
"Label": "Cheshire",
"Url": "/search?cid=7"
},
{
"Id": "24",
"Label": "Greater Manchester",
"Url": "/search?cid=24"
}
],
"Locations": [
{
"Id": "12061",
"Label": "Cheselbourne, Dorset (DT2 7)",
"Url": "/search?lid=12061"
},
{
"Id": "12062",
"Label": "Chesham, Buckinghamshire (HP5 1)",
"Url": "/search?lid=12062"
},
{
"Id": "12063",
"Label": "Chesham, Greater Manchester (BL9 6)",
"Url": "/search?lid=12063"
},
{
"Id": "12064",
"Label": "Chesham Bois, Buckinghamshire (HP6 5)",
"Url": "/search?lid=12064"
},
{
"Id": "12065",
"Label": "Cheshunt, Hertfordshire (EN8 9)",
"Url": "/search?lid=12065"
},
{
"Id": "12066",
"Label": "Chesley, Kent (ME9 7)",
"Url": "/search?lid=12066"
},
{
"Id": "12067",
"Label": "Cheslyn Hay, Staffordshire (WS6 7)",
"Url": "/search?lid=12067"
},
{
"Id": "12068",
"Label": "Chessetts Wood, Warwickshire (B94 6)",
"Url": "/search?lid=12068"
},
{
"Id": "12069",
"Label": "Chessington, Kingston upon Thames - Greater London (KT9 2)",
"Url": "/search?lid=12069"
},
{
"Id": "12070",
"Label": "Chessmount, Buckinghamshire (HP5 1)",
"Url": "/search?lid=12070"
}
]
}
The API I'm calling returns results based on my search term, so I know that all of the results in the nested objects are matches - my problem is how to access these objects ('Developments', 'Counties' and 'Locations') so that the autocomplete widget can pick up the 'Label' values?
Thanks,
Robin
Ok - here's what you can do:
//put all the keys you want to pull out of your json in an array
var props = [
"Locations", "Counties", "Developments"
];
//empty array for your autocomplete
var labels = [];
//loop thru all the properties you care about
$.each(props, function () {
$.each(source[this], function () {
//and pull out all the labels and add them to the labels array
labels.push(this.Label)
});
});
$("#autocomplete").autocomplete({
source: labels
});
and to see it all in action I created a quick fiddle
http://jsfiddle.net/fr5yb3n0/
Related
I'm trying to access the "title" section (key?) of this JSON object using NodeJS. I can return the entire object, but every time I try to access the key, undefined is returned.
[
[
{
"id": 119,
"title": "Roadhouse",
"url": "https://funsite.com/2021/03/20/funny/",
"date": "2021-03-20"
}
],
[
{
"id": 208,
"title": "New Sites",
"url": "https://coolsitestuff.com/notes/coolsite/",
"date": "2021-03-17"
}
],
[
{
"id": 13,
"title": "woah sites!!",
"url": "https://now.lettuce.com/then/2021-0000/",
"date": "2021-03-07"
}
],
[
{
"id": 120,
"title": "mynewalbumn",
"url": "https://notarealsite.com/2021/03/06/next-album/",
"date": "2021-03-06"
}
],
[
{
"id": 140,
"title": "fightingthemans",
"url": "http://fightcats.com/2021/03/06/keyfights",
"date": "2021-03-06"
}
],
[
{
"id": 14,
"title": "biggest lettuce youll ever see",
"url": "https://morelettuce.com/then/biggestlettuceleaf/",
"date": "2021-02-28"
}
]
]
NodeJS
const fs = require('fs')
fs.readFile('./data/links.json', 'utf8', (err, fsToString) => {
let data = JSON.parse(fsToString);
console.log(data.map(link => link[link.url]))
})
I've tried for loops and indexing that way but I haven't been able to get anything out of it.
You have 2 arrays, either loop over both of them or access it using index
let data =[
[
{
"id": 119,
"title": "Roadhouse",
"url": "https://funsite.com/2021/03/20/funny/",
"date": "2021-03-20"
}
],
[
{
"id": 208,
"title": "New Sites",
"url": "https://coolsitestuff.com/notes/coolsite/",
"date": "2021-03-17"
}
]
]
data.map(link=> console.log(link[0].url))
Your json is array of array objects, you need to access all arrays by index, you can use flatMap and map methods.
var data = [
[{
"id": 119,
"title": "Roadhouse",
"url": "https://funsite.com/2021/03/20/funny/",
"date": "2021-03-20"
}],
[{
"id": 208,
"title": "New Sites",
"url": "https://coolsitestuff.com/notes/coolsite/",
"date": "2021-03-17"
}],
[{
"id": 13,
"title": "woah sites!!",
"url": "https://now.lettuce.com/then/2021-0000/",
"date": "2021-03-07"
}],
[{
"id": 120,
"title": "mynewalbumn",
"url": "https://notarealsite.com/2021/03/06/next-album/",
"date": "2021-03-06"
}],
[{
"id": 140,
"title": "fightingthemans",
"url": "http://fightcats.com/2021/03/06/keyfights",
"date": "2021-03-06"
}],
[{
"id": 14,
"title": "biggest lettuce youll ever see",
"url": "https://morelettuce.com/then/biggestlettuceleaf/",
"date": "2021-02-28"
}]
];
console.log(data.flatMap(i=>i.map(f=>f.url)))
Your current code is trying to access an undefined object property.
Solution:
Replace the link[link.url] for link[0].url. So that the full line is
console.log(data.map(link => link[0].url))
Or if you want the titles:
console.log(data.map(link => link[0].title))
console.log(
data.flat().map(link=>link.url)
);
console.log(
data.map(item=>item[0].url)
);
From what I see your JSON file holds an array of arrays and each nested array contains one object. Therefore data.map(link => link[0].title) should return array of titles
You have an array of arrays and each one with just one position. For the code you posted you're just missing the index of each element.
If you change your code to this you'll get the array with the URL's you're looking for
fs.readFile('./example.json', 'utf8', (err, fsToString) => {
let data = JSON.parse(fsToString);
console.log(data.map(link => link[0].url))
})
Happy coding ;)!
Hi I have a json array in the below format.
{
"data": {
"title": "MainNode"
},
"children": [{
"data": {
"title": "Firstchild",
"description": "Texttexttext"
},
"children": [{
"data": {
"title": "Firstchildschild",
"description": "Texttexttext"
},
"children": [{
"data": {
"title": "FirstchildschildsChild",
"description": "Texttexttext"
}
}]
}, {
"data": {
"title": "FirstchildsSecondchild",
"description": "Texttexttext"
},
"children": [{
"data": {
"title": "FirstchildsSecondchildsChild",
"description": "Texttexttext"
}
}]
}]
}]
}
I have to read the array based on the title text value and list that particular data and its sub data.
For eg. If my input (title value will get from the http URL as follows) is "Firstchild/Firstchildschild/" then I have to list FirstchildschildsChild and its description.
If my input is input is /Firstchild/ then I have to list Firstchildschild & FirstchildsSecondchild data and its sub childs name.
Using jquery how can I fetch records as I mentioned above. Please advise the best way to process this json instead of using lot of loops?
Ok just for these necessities (and believe this is really a big necessity) i had invented an Object method called Object.prototype.getNestedValue() which dynamically fetches you the nested value from deeply nested Objects. All you need to provide is a string for the properties and a number for the array indices in the proper order. OK lets see...
Object.prototype.getNestedValue = function(...a) {
return a.length > 1 ? (this[a[0]] !== void 0 && this[a[0]].getNestedValue(...a.slice(1))) : this[a[0]];
};
var JSONobj = {
"data": {
"title": "MainNode"
},
"children": [{
"data": {
"title": "Firstchild",
"description": "Texttexttext"
},
"children": [{
"data": {
"title": "Firstchildschild",
"description": "Texttexttext"
},
"children": [{
"data": {
"title": "FirstchildschildsChild",
"description": "Texttexttext"
}
}]
}, {
"data": {
"title": "FirstchildsSecondchild",
"description": "Texttexttext"
},
"children": [{
"data": {
"title": "FirstchildsSecondchildsChild",
"description": "Texttexttext"
}
}]
}]
}]
},
value = JSONobj.getNestedValue("children",0,"children",0,"data","title");
console.log(value); // Firstchildschild
var a = "children",
b = 0,
c = "data",
d = "title";
value2 = JSONobj.getNestedValue(...[a,b,a,b,c,d])
console.log(value2); // Firstchildschild
It also has a sister called Object.prototype.setNestedValue().
var obj = jQuery.parseJSON( '
"data": {
"title": "MainNode"
},
"children": [{
"data": {
"title": "Firstchild",
"description": "Texttexttext"
},
"children": [{
"data": {
"title": "Firstchildschild",
"description": "Texttexttext"
},
"children": [{
"data": {
"title": "FirstchildschildsChild",
"description": "Texttexttext"
}
}]
}, {
"data": {
"title": "FirstchildsSecondchild",
"description": "Texttexttext"
},
"children": [{
"data": {
"title": "FirstchildsSecondchildsChild",
"description": "Texttexttext"
}
}]
}]
}]
}' );
alert( obj.name === "data" );
You have to parse the element
obj.name === "data"
in the next link
What I am trying to do exceeds my knowledge. Thank you all for your time and help, it is a great pleasure to have the support of such a large community of great developers.
The problem
I need to loop over an object (JSON response) to determine which data is true and then edit the html with the results.
json object is:
var data = {
"total": 4,
"limit": 50,
"questions": [{
"date_created": "2015-06-29T18:24:25.000-04:00",
"item_id": "MLA567045929",
"seller_id": 186626557,
"status": "UNANSWERED",
"text": "Pregunta de Testeo, user 2.",
"id": 3612747353,
"deleted_from_listing": false,
"hold": false,
"answer": null,
"from": {
"id": 186625262,
"answered_questions": 0
}
}, {
"date_created": "2015-06-29T18:30:16.000-04:00",
"item_id": "MLA567045929",
"seller_id": 186626557,
"status": "UNANSWERED",
"text": "Lorem ipsum dolor sit amet",
"id": 3612938882,
"deleted_from_listing": false,
"hold": false,
"answer": null,
"from": {
"id": 186625262,
"answered_questions": 0
}
}, {
"date_created": "2015-06-29T18:30:35.000-04:00",
"item_id": "MLA567045929",
"seller_id": 186626557,
"status": "UNANSWERED",
"text": "an est odio timeam quaerendum",
"id": 3612752695,
"deleted_from_listing": false,
"hold": false,
"answer": null,
"from": {
"id": 186625262,
"answered_questions": 0
}
}, {
"date_created": "2015-06-29T18:31:32.000-04:00",
"item_id": "MLA567045929",
"seller_id": 186626557,
"status": "ANSWERED",
"text": "Responder esta pregunta",
"id": 3612753455,
"deleted_from_listing": false,
"hold": false,
"answer": {
"text": "Pregunta respondida",
"status": "ACTIVE",
"date_created": "2015-06-29T18:31:58.000-04:00"
},
"from": {
"id": 186625262,
"answered_questions": 1
}
}],
"filters": {
"limit": 50,
"offset": 0,
"is_admin": false,
"sorts": [],
"caller": 186626557,
"seller": "186626557"
},
"available_filters": [{
"id": "item",
"name": "Item",
"type": "text"
}, {
"id": "from",
"name": "From user id",
"type": "number"
}, {
"id": "totalDivisions",
"name": "total divisions",
"type": "number"
}, {
"id": "division",
"name": "Division",
"type": "number"
}, {
"id": "status",
"name": "Status",
"type": "text",
"values": ["BANNED", "CLOSED_UNANSWERED", "DELETED", "DISABLED", "UNDER_REVIEW"]
}],
"available_sorts": ["item_id", "from_id", "date_created", "seller_id"]
};
The result I'm looking for is:
Of the data object, I need to extract questions with the status unanswered and the id field associated with these unanswered questions.
"questions1":[{ "status" : "UNANSWERED",
"id" : 3612747353}],
"questions2":[{ "status" : "UNANSWERED",
"id" : 3612938882}],
...
Based on what I've searched, I've tried with loops, for in, and each without success.
Any suggestions or ideas on how I could achieve the desired result? I need to apply this example to several objects.
Try some handy list processing functions to simplify it conceptually. The filter and map functions will help. The function I provided to filter tells it to only let through items that meet the condition of having an unanswered status. The function I provided to map turned all the objects that came out of filter into just their ids.
data["questions"].filter(function(obj) {
return obj["status"] === "UNANSWERED";
}).map(function(obj) {
return obj["id"];
});
var results = [];
for (var question in data.questions) {
if (data.questions[question].status === "UNANSWERED") {
results.push({
"status" : data.questions[question].status,
"id" : data.questions[question].id
});
}
}
// Now results contains an array of unanswered questions,
// with just their status & id.
You can just loop through the questions and save the ids you want to an array:
var questions = data.questions;
var unanswered = [];
for(var i = 0, len = questions.length; i < len; i++) {
if(questions[i].status === 'UNANSWERED') {
unanswered.push(questions[i].id);
}
}
unanswered will be an array of unanswered question ids. You don't need to save the status; you know they are all 'UNANSWERED'.
i have used $.getJSON for getting json data on pagebeforeshow but it is not working as it have to.
$(document).on('pagebeforeshow', '#inpGrid', function(e) {
alert("inpGrid");
var tat_url = "http://192.168./html5/Demo/json/list.json";
var url = "http://api.openweathermap.org/data/2.5/forecast?lat=35&lon=139&callback=?" ;
$.getJSON(tat_url, function(res) {
console.log(res)
});
});
the code is as above, when using url in $.getJSON it is working, wheras as using tat_url it is not working.
the http://192.168./html5/Demo/json/list.json consists as follows
{
"response": {
"respCode": 0,
"output": {
"delAction": "OP",
"delTmplt": "sibcVizEdit",
"title": "List TATs",
"layout": "grid",
"srvObjRef": "iawme1/IAWMblztnExpert-ListSIBCs_MB1412577249595",
"startIndex": "0",
"recsPerPage": "18",
"noPages": "1",
"curPageNo": "1",
"fieldInfo": [
{
"label": "Name",
"type": "STRING"
}
{
"label": "Alias",
"type": "STRING"
}
{
"label": "Datatype",
"type": "STRING"
}
{
"label": "Default Value",
"type": "STRING"
}
{
"label": "Visibility",
"type": "STRING"
}
],
"records": [
{
"Name": "psngrType"
"Alias": "Pasngr Type"
"Datatype": "STRING"
"Default Value":"CC"
"Visibility": "0"
},
{
"Name": "flightNo"
"Alias": "Flight No"
"Datatype": "STRING"
"Default Value":"$RV_flightNo"
"Visibility": "0"
}
],
"relServices": {
"AServices": [
{
"ref": "IAWMblztnExpert-ListSIBCs-UpdateBizContext_MB",
"title": "Update SIBC",
"desc": "",
"srvRef": "IAWMblztnExpert-ListSIBCs-UpdateBizContext_MB",
"slctdOffsets": "0"
},
{
"ref": "IAWMblztnExpert-ListSIBCs-ListIICsInSIBC_MB",
"title": "List IICs",
"desc": "",
"srvRef": "IAWMblztnExpert-ListSIBCs-ListIICsInSIBC_MB",
"slctdOffsets": "0"
},
{
"ref": "IAWMblztnExpert-ListSIBCs-Deploy SIBC_MB",
"title": "Deploy",
"desc": "",
"srvRef": "IAWMblztnExpert-ListSIBCs-Deploy SIBC_MB",
"slctdOffsets": "0"
}
]
}
}
}
}
Can someone help me please thanks.
Your JSON contain syntax errors, look your ''fieldInfo'' node. You didn't seperate your differents object by ,
Example:
{
"label": "Name",
"type": "STRING"
},
{
"label": "Alias",
"type": "STRING"
}
instead of
{
"label": "Name",
"type": "STRING"
}
{
"label": "Alias",
"type": "STRING"
}
Use online JSON validator if you need check rest of your json file easily : http://jsonlint.com/
I have a model in which values are stored in following format:--
Language-count=3
[0]
-ID="1"
-Name="French"
[1]
-ID="2"
-Name="English"
[2]
-ID="3"
-Name="Hindi"
Titles-count=2
[0]
-ID="1"
-Name="Video1"
[1]
-ID="2"
-Name="Video2"
Countries-count=2
[0]
-ID="1"
-Name="India"
[1]
-ID="2"
-Name="USA"
and I have to convert this model in given json format:-
var models = [
{
name: 'Language',
values: [
'English',
'French',
'Hindi'
]
},
{
name: 'Title',
values: [
'Title 1',
'Title 2'
]
},
{
name: 'Countries',
values: [
'India',
'UK'
]
}
];
In above json format I have hard coded those values of Languages,countries and Titles but I have to fetch it from the above model which I have already given.
The json Format which I am getting is following:--
{
"ID": 1,
"DealID": 1,
"Title": "Position1",
"Titles": [
{
"Icon": "hdtv",
"Name": "\nWedding Bells & Farewells\n",
"ID": 12
},
{
"Icon": "hdtv",
"Name": "Delta Farce",
"ID": 5
},
{
"Icon": "hdtv",
"Name": "Doe B: Let Me Find",
"ID": 9
}
],
"Episodes": [
{
"Icon": "episode",
"Name": "Sparkle",
"ID": 4
},
{
"Icon": "episode",
"Name": "Sparks Fly Out",
"ID": 2
},
{
"Icon": "episode",
"Name": "Uploads by Filmi Gaane",
"ID": 7
}
],
"Assets": [
{
"Icon": "file-o",
"Name": "Best of Javed Akhtar - Jukebox 2 - Javed Akhtar Top 10 Hit Songs",
"ID": 10
},
{
"Icon": "file-o",
"Name": "Ep 105 - Sin Say Shun Awards After Party additional image 1",
"ID": 4
},
{
"Icon": "file-o",
"Name": "Ep 105 - Sin Say Shun Awards After Party box cover",
"ID": 3
}
],
"Documents": [],
"Languages": [
{
"Icon": "globe",
"Name": "Albanian",
"ID": 70
},
{
"Icon": "globe",
"Name": "Amharic",
"ID": 96
}
],
"Territories": [],
"Countries": [
{
"Icon": "globe",
"Name": "Afghanistan",
"ID": 2
},
{
"Icon": "globe",
"Name": "Albania",
"ID": 3
},
{
"Icon": "globe",
"Name": "Algeria",
"ID": 4
}
],
"Rights": [
{
"Icon": "leaf",
"Name": "Ancillary",
"ID": 23
},
{
"Icon": "leaf",
"Name": "Finshed Episode Rights",
"ID": 20
},
{
"Icon": "leaf",
"Name": "Format Group - DO NOT USE",
"ID": 63
}
],
"Contributors": [],
"Transmissions": [],
"Available": null
}
It would be best to write a simple parser and transform your data type to JSON - which would additionally allow you to reuse the parser in the future, and convert it to other data types easily for instance.
You could look at the various YAML parsers for inspiration, which would use a similiar technique for your data set's language.
Alternatively you can create a 'hack' and just keep splitting things up if your data format is always of this format, and doesn't allow arbitrary value nesting.
List personel = new List();
var client = new RestClient("your adres");
var request = new RestRequest(Method.GET);
request.AddHeader("Postman-Token", "2893de4a-457e-46a7e8efb025");
request.AddHeader("cache-control", "no-cache");
request.AddHeader("Content-Type", "application/json");
request.AddHeader("token", "a23a80f7-3323-4594056");
IRestResponse response = client.Execute(request);
JObject deger = JObject.Parse(response.Content);
var toplam = deger["data"]["data"].Count();
string jenp = toplam.ToString();
for (int i = 0; i < toplam; i++)
{
Personeller data = new Personeller();
data.Adi = deger["data"]["data"][i]["adi"].ToString();
data.Soyadi = deger["data"]["data"][i]["soyadi"].ToString();
data.tckimlikno = (long)deger["data"]["data"][i]["tckimlikno"];
personel.Add(data);
}