finding nested object value in java script - javascript

JSON file from URL
{
"1": [
{
"actions": ["OUTPUT:2" ],
"idle_timeout": 0,
"cookie": 0,
"packet_count": 2,
"hard_timeout": 0
}
}
JavaScript
function myFunction() {
//alert("INTo function");
$.ajax({
url: "http://127.0.0.1:3000/flow",
cache: false,
success: function(data) {
$("#flow").append(data["1"].actions.OUTPUT[i]);
$("#flow").append(data["1"].idle_timeout);
$("#flow").append(data["1"].cookie);
$("#flow").append(data["1"].packet_count);
$("#flow").append(data["1"].hard_timeout);
}
});
}
This is the JavaScript code which I have used it, to find values of the object inside the nested JSON response coming from a URL.

Your sample does not look like valid json. Since the value of "1" is an array, you should try to access it via the index. e.g.$("#flow").append(data["1"][0].idle_timeout)

The code used to find the values inside the nested JSON object is actually incorrect.
You must use data["1"][0].actions[0].OUTPUT to retrieve the value 2.

Related

Access array inside JSON object using Axios Vue JS

I need to access arrays inside JSON object and save into different arrays. I tried few ways but no luck.
I could get all other values without any problem but when it comes to arrays I couldn't retrieve those.
I feel the way I try to access arrays inside JSON object might be wrong and but I couldn't figure it out
Here is JSON object
{
"packId":51,
"shortCode":"TTY",
"packDescription":"TTY Des",
"startDate":"2020-09-01",
"endDate":"2020-09-08",
"validityValue":30,
"validityType":"Hours",
"expiryAction":true,
"expirySMS":64,
"activationSMS":64,
"deactivationSMS":64,
"subscriptionSMS":0,
"deactivationAction":true,
"deactivationShortCode":"DEACT TTY",
"deprovisionOnExpiry":true,
"deleteByPackType":true,
"packType":{
"packTypeId":2,
"name":"Facebook"
},
"timeBands":[
{
"timeBandId":1,
"start":"8:00",
"end":"23:00",
"timeBand":"8:00-23:00"
},
{
"timeBandId":2,
"start":"8:00",
"end":"20:00",
"timeBand":"8:00-20:00"
}
],
"activationTypes":[
{
"activationTypeId":1,
"name":"SMS"
},
{
"activationTypeId":2,
"name":"Web"
}
],
"channels":[
{
"channelId":1,
"name":"hShenid"
},
{
"channelId":2,
"name":"Genesis"
}
],
"users":[
]
}
Axios Call
getPackById(id)
{
return axios.get(`${API_URL}/pack/get/${id}`);
}
refreshPack()
{
PackComposeDataService.getPackById(this.id).then((res)=>
{
//I can access these values without any problem
this.deleteByPackType= res.data.deleteByPackType,
this.packTypeValues=res.data.packType,
this.shortCode= res.data.shortCode,
this.packDescription= res.data.packDescription,
this.startDate= res.data.startDate,
this.endDate= res.data.endDate,
this.subscriptionSMS= res.data.subsNotificationValues["id"],
this.validityValue= res.data.validityValue,
this.validityType= res.data.validityType,
this.actionOnExpiry= res.data.expiryAction,
this.expirySMS= res.data.expiryNotificationValues,
this.activationSMS= res.data.activationNotificationValues,
this.deactivationAction= res.data.deactivationAction,
this.deactivationShortCode= res.data.deactivationShortCode,
this.deactivationSMS= res.data.deactivationNotificationValues,
this.deprovisionOnExpiry= res.data.deprovisionOnExpiry,
//I need to get these arrays
this.timeBandValues= res.data.timeBands,
this.activationTypes= res.data.activationTypes,
this.channels= res.data.channels,
this.users= res.data.users
});
I understand you want to take only the timeBand string of each of the arrays (or the activationType, eventually).
If that's the case, you may want to map to convert each object in the array to a simple string:
// ...
this.timeBandValues = res.data.timeBands.map(o => o.timeBand) // you're going to get ["8:00-23:00", "8:00-20:00"]
// ...

Is there anyway to update an exising array defined inside HTML?

There is a static array which should be dynamically updated based upon click event.
I am able to get the dynamic value in an array format using Ajax but finding difficulties in setting it to the existing variable.
Ajax returns the below array
echo json_encode($arry);
// ["2","1","1","0","1","0"]
$.post( "ajaxcall.php", { ids: id })
.done(function( returnedArray){
//returnedArray looks like ["2","1","1","0","1","0"]
datasets: [{
//data: [10,12,33,50,12,34]
data: returnedArray
}]
},
But after the click event, returnedArray does not get interpreted to place the value.
Bacialy the result should look like below:
data: ["2","1","1","0","1","0"]
Use the assignment operator instead of :
datasets = [{
//data: [10,12,33,50,12,34]
data: returnedArray
}]

Can't access nested json elements with javascript

I'm really stuck on how to access nested elements of a json response that I'm getting from my api. I validated the json and it shows as valid.
For instance, how do I access the numFound attribute? Here's my code that is not working:
$.ajax({
url: "/api/SearchAPI/infopop?id=" + songID,
datatype:"json",
method: "get"
}).done(function (data) {
var obj = JSON.parse(data);
alert(obj); /* This displays the entire json response
alert(obj.response.numFound) /* This does not work
alert(data.response.numFound) /* This does not work
Here's the response I'm trying to access
{
"responseHeader":{
"status":0,
"QTime":0,
"params":{
"q":"*:*",
"indent":"off",
"fl":"Name,Description,Keywords,ISRC,Instruments,Lyrics,Bpm,Vocal,Tempo,Key,TV_Genres,Music_Genres,length\r\n,Writers,profileImagePath\r\n,Publishers\r\n,songImagePath\r\n,Band_Styles",
"start":"0",
"callback":"?\r\n",
"fq":[
"id:00106c8c-7e21-4e75-80da-cdff8e6d3d44",
"publicflag:1",
"pubname:komposed"
],
"rows":"10",
"version":"2.2",
"wt":"json"
}
},
"response":{
"numFound":1,
"start":0,
"docs":[
{
"profileImagePath":[
"https://komposed.blob.core.windows.net/jrock-1873564a-d409-4370-80d8-23dc97114f18/songimage/f557110f-4ad3-4353-a1b3-3ba70d52e8f0?sv=2014-02-14&sr=b&sig=Q3ywrwEa6URp%2FPCvK0Ngesza8PBhMEmE5ONeKhw8vE4%3D&st=2016-06-16T16:49:45Z&se=2066-06-16T16:54:45Z&sp=r&rsct=application%2Foctet-stream&rscd=attachment%3B%20filename%3Dredneck.jpeg"
],
"songImagePath":[
"https://komposed.blob.core.windows.net/jrock-1873564a-d409-4370-80d8-23dc97114f18/songimage/f0c00dcd-69f9-42af-b236-4a53f0d78e76?sv=2014-02-14&sr=b&sig=oF0STMDddyuJiNZO%2BE78sYtbboC4ic%2Fl4bR5ESBFouE%3D&st=2016-06-16T16:48:59Z&se=2066-06-16T16:53:59Z&sp=r&rsct=application%2Foctet-stream&rscd=attachment%3B%20filename%3DTENSION%20LAST%20MAN.jpg"
],
"Name":[
"Bottle Service Tension"
],
"Description":[
"Cool crime scene track with a chill night club vibe"
],
"Bpm":[
90
],
"Vocal":[
"Acapella"
],
"Tempo":[
"Fast"
],
"Writers":[
"Justin Sirota|100.00|"
],
"Keywords":[
"club, crime, investigation, cool, lounge, pulse"
],
"TV_Genres":[
"Tension"
]
}
]
}
}
Just use obj.numFound. response is your data argument.
$.ajax({
...
}).done(function (response) {
alert(response.numFound)
...
Also, since you're telling jQuery (assuming this based on the code) that the response is of JSON type via datatype:"json", you don't need to do JSON.parse on it.
Turns out the issue was in my API. I was returning json as a string instead of an object. Once I did that, javascript was able to reference the json elements. Thanks for trying to help!

jQuery: Get JSON error

I'm trying to get certain elements from a JSON file but I'm just not able to do so, I've tried different ways, this is the JSON file:
// data.json
{
"stuff": [
{
"userId": 1,
"date": "19 Oct 2014",
"content": "#New Hello on g.co/ABC",
"entities": {
"hashtags": ["#New"],
"urls": ["g.co/ABC"]
}
}
],
"user": {
"avatar": "/assets/avatar.jpg",
"name": "Daniel"
}
}
Now my jQuery code is:
$(document).ready(function(){
$.getJSON('data.json', function(data) {
//console.log(data);
$.each(data,function(i,item){
console.log(item.stuff.content); // I want to print 'content'
});
});
});
And all I get is an Uncaught error type:
What am I doing wrong? Thanks in advance
stuff is an array of object.
To access item of an array you have to access it via index
like this
console.log(data.stuff[0].content);
JSFIDDLE
May be you are iterating an object instead of array of object
If data is an object then try like this
$.each(data.stuff,function(i,item){
console.log(item.content);
});
JSFIDDLE
This should work:
$.getJSON('data.json', function(data) {
console.log(data['stuff'][0]['content']);
}
It is getting the stuff element of the JSON object then the first element of that pair, since the pair of key "stuff" is an array of JSON Objects. Then from that last JSON object, its grabbing content.
You json data is not an array. so you don't need to use each. But stuff is an array so take it's specific index or loop through it.
$(document).ready(function(){
$.getJSON('data.json', function(data) {
console.log(data.stuff[0].content);
//or loop through like
//$.each(data.stuff,function(i,item){
// console.log(item.content);
//});
});
});

twitter typeahead 0.9.3 remote return URL and json object

in bootstrap 2, I used the following code to post a json object,
$('#typeahead').typeahead({
source: function (query, process) {
var URL = 'http://localhost:8080/autocomplete/search/';
var query = {"t:jsonStringField": {
"name": "model",
"value": "fusion"
},
"t:jsonStringFilter": [
{"name": "year","value": "2009"},
{"name": "make","value": "ford"}
]
};
return $.getJSON(URL,
{ query: JSON.stringify(query)},
function (data) {
return process(data);
});
}
});
Now in twitter tyeahead 0.9.3 they have done away with the source concept and moved to a remote concept, but unfortunately I do no know how to work with it.
$(".typeahead").typeahead({
remote : {
url: 'http://localhost:8080/autocomplete/search/',
replace: function(uri, query) {
var query = {"t:jsonStringField": {
"name": "model",
"value": "fusion"
},
"t:jsonStringFilter": [
{"name": "year","value": "2009"},
{"name": "make","value": "ford"}
]
};
return uri + JSON.stringify(query);
},
filter: function(response) {
return response.matches;
}
return process(resultList);
}
}
Unfortunately it doesn't work, how do I just post the JSON object rather than appending it to the string? Thanks.
In your original code you use $.getJSON. This will send a request (and expects json as result) to: http://localhost:8080/autocomplete/search/?query=%7B%22t%3AjsonStringField%22%3A%7B%22name%22%3A%22model%22%2C%22value%22%3A%22fusion%22%7D%2C%22t%3AjsonStringFilter%22%3A%5B%7B%22name%22%3A%22year%22%2C%22value%22%3A%222009%22%7D%2C%7B%22name%22%3A%22make%22%2C%22value%22%3A%22ford%22%7D%5D%7D
To do the same for Twitter's Typeahead call your replace function of your remote data should return a valid url. In your function the ?query= part of the url is missing.
You will have to set: url: 'http://localhost:8080/autocomplete/search/?query=',
You also will have to urlencode you json input maybe.
Note: you will not need the line return process(resultList); You will have to use the filter function to convert your json results to valid data:
The individual units that compose datasets are called datums. The
canonical form of a datum is an object with a value property and a
tokens property.
you could use templates to style your dropdown results, see: http://twitter.github.io/typeahead.js/examples/
By default, the dropdown menu created by typeahead.js is going to look
ugly and you'll want to style it to ensure it fits into the theme of
your web page.
You will need the additional CSS from https://github.com/jharding/typeahead.js-bootstrap.css to style the default dropdown for Bootstrap.

Categories

Resources