fetch data from nested JSON object in a single line - javascript

This is my JSON data ....
{"comp1":["$.Create_Keypair1_Keypair_name"]}
I want to get the value "Create_Keypair1_Keypair_name".but all the keys and values are dynamic.but the object always have single data.
I have Object.keys(temp).It shows only ["comp1"] i need
$.Create_Keypair1_Keypair_name only....

Try this:
var data = {"comp1":["$.Create_Keypair1_Keypair_name"]}
for (var key in data) {
console.log(data[key])
}
This will log $.Create_Keypair1_Keypair_name.

From what I am understanding each object will have a single value. If the is the case then you do not need the array in the object. You can do this.
var tempy = {"comp":"ksmdfnsfdnsdfn"}
Then do this to ge the value.
tempy.comp
Or if you need the keys.
Object.keys(tempy)

you might be looking for this
var temp = {"comp1":["$.Create_Keypair1_Keypair_name"]}
Object.keys(temp).forEach(function(key){
console.log(temp[key]);
});

Related

What is the correct way to handle this data using jQuery?

I have a list of html elements with data attributes, which I would like to assemble into a jQuery object and manipulate the values.
What is the best way to dynamically add these in an each loop so that I can easily access the data as so: data.name and data.name.prop?
I want all the naming conventions to be dynamic and based on the data.
I based my code on the top answer from here: How to create dynamically named JavaScript object properties?
So far I have:
$('.licences-list .data div').each(function(index) {
var data = {}
cats[$(this).find('p').data('cat')] = $(this).find('p').data('catname')
cats.push(data)
})
But when I try to iterate over the data array, like so:
$.each(cats, function(key, value){
$('<div class="card"><p>'+value+'</p></div>').appendTo('#commercial-licenses');
});
I just get [object Object] output... and I'm not sure why!
var data = {}
cats[$(this).find('p').data('cat')] = $(this).find('p').data('catname')
Each time you loop through, you're actually just adding an empty object (data) to your array (cats). You're then assigning a named property to that array (cats) which $.each has no idea about (it ignores them because it's iterating over an actual array).
My guess is you want an object map which is something like: var cats = { "f1": "feline 1", "f2": "feline " };
In that case what you want is:
var cats = {};
$('.licences-list .data div').each(function(index) {
cats[$(this).find('p').data('cat')] = $(this).find('p').data('catname')
})
If you want an array that contain more values than just strings (or whatever data you have added to the element), you create new objects each time and append them to the cats array:
var cats = [];
$('.licences-list .data div').each(function(index) {
cats.push({
'id': $(this).find('p').data('cat'),
'name': $(this).find('p').data('catname')
});
})
This will then give you an array that you can use $.each over, and access the values using: value.id, value.name
Don't over complicate it.
$('.div').attr('data-attribute', 'data-value');
using your example:
$('.licences-list .data div').attr('attribute-name', 'attribute-value');

Parsing JSON and loading into array

JSON-https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo
I am trying to take the JSON from the above link and place it in the following format(date,open,high,low,close)...
[
[1277424000000,38.58,38.61,37.97,38.10],
[1277683200000,38.13,38.54,37.79,38.33],
[1277769600000,37.73,37.77,36.33,36.60],
[1277856000000,36.67,36.85,35.72,35.93],
]
The date does not need to be Epoch time.
My code....
$.getJSON('https://www.alphavantage.co/query?
function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo', function(data) {
//Get the time series data
var timeseries = data['Time Series (Daily)']
var ohlcarray = [];
//Loop through each time series and convert it to JSON format
$.each(timeseries, function(key, value) {
var ohlcdata=[];
ohlcdata[0]=value[0];//date
ohlcdata[1]=value[1];//open
ohlcdata[2]=value[2];//high
ohlcdata[3]=value[3];//low
ohlcdata[4]=value[4];//low
ohlcarray.push(ohlcdata);
});
console.log(ohlcarray[0]);//test if worked properly
});
The output....
[undefined, undefined, undefined, undefined, undefined]
value[x] returns undefined. Any ideas on why this happens?
Thanks!
The reason is that in the each loop, the value is not a list but an object. To access it, you'd have to grab it using keys.
ohlcdata[0] = key; //date
ohlcdata[1] = value['1. open']; //open
ohlcdata[2] = value['2. high']; //high
ohlcdata[3] = value['3. low']; //low
ohlcdata[4] = value['4. close']; //low
https://jsfiddle.net/koralarts/7c2fkf93/2/
At this point it is already JSON. As Patrick mentioned, getJSON automatically parses json. You will need to access it with the array bracket notation since there are spaces in the property name.
var timeSeries = data['Time Series (Daily)'];
See ex: https://jsfiddle.net/dz0phhn2/6/

JavaScript, JSON, referencing by name

How do you reference a JSON object in JavaScript?
I have a JSON response from a Rest web service and trying to reference the contents of the response which I have parsed to JSON by way JSON.Parse(response)
Sample JSON:
{
"HotelListResponse":{
"customerSessionId":"",
"numberOfRoomsRequested":1,
"moreResultsAvailable":true,
"cacheKey":"",
"cacheLocation":"",
"cachedSupplierResponse":{
"#supplierCacheTolerance":"NOT_SUPPORTED",
"#cachedTime":"0",
"#supplierRequestNum":"101",
"#supplierResponseNum":"",
"#supplierResponseTime":"",
"#candidatePreptime":"14",
"#otherOverheadTime":"",
"#tpidUsed":"",
"#matchedCurrency":"true",
"#matchedLocale":"true"
},
"HotelList":{
"#size":"20",
"#activePropertyCount":"101",
"HotelSummary":[
{
"name":"name1"
},
{
"name":"name2"
}
]
}
}
}
How can I, for example reference the customerSessionId? And the second HotelSummary name?
For customerSessionId I have tried jsonObject.customerSessionId which returns undefined. For the second hotel summary name I have tried jsobObject.HotelList.HotelSummary[1].name which is undefined too.
Given the JSON string above parsed and assigned to a variable as such:
var response = JSON.Parse(jsonString);
you should be able to access it like this:
var customerSessionId = response.HotelListResponse.customerSessionId;
Here's the working solution fiddle
As you can see, you need to reference HotelListResponse,
so if your var result holds your json object, then you can fetch the values by using
var first = result.HotelListResponse.customerSessionId
var second = result.HotelListResponse.HotelList.HotelSummary[1].name

extract single variable from JSON array

I hope my question is not as stupid as I think it is...
I want to extract (the value of) a single variable from an JSONarray. I have this jquery code
$(document).ready(function(){
$("#gb_form").submit(function(e){
e.preventDefault();
$.post("guestbook1.php",$("#gb_form").serialize(),function(data){
if(data !== false) {
var entry = data;
$('.entries').prepend(entry);
}
});
});
});
the content of data looks like this ("MyMessage" and "MyName" are values written in a simple form from user):
[{"message":"MyMessage","name":"MyName"}]
the var "entry" should give (more or less) following output at the end:
"Send from -MyName- : -MyMessage-"
I'm not able to extract the single array values from data. I tried things like that:
var message = data['message'];
var name = data['name']
var entry = "Send from" + name + ":" +message;
but that gives "Send from undefined: undefined"
Hope you can help me with that.
you can do like this to get first item of array:
var msg = "Send from"+data[0].name + " "+data[0].message;
console.log(msg );
SAMPLE FIDDLE
UPDATE:
as you are using $.post you will need to explicitly parse response as json:
$.post("guestbook1.php",$("#gb_form").serialize(),function(data){
var response = jQuery.parseJSON(data);
var msg = "Send from"+response [0].name + " "+response [0].message;
console.log(msg );
});
To access an array you use the [] notation
To access an object you use the . notation
So in case of [{JSON_OBJECT}, {JSON_OBJECT}]
if we have the above array of JSON objects in a variable called data, you will first need to access a particular Json Object in the array:
data[0] // First JSON Object in array
data[1] // Second JSON Object in array.. and so on
Then to access the properties of the JSON Object we need to do it like so:
data[0].name // Will return the value of the `name` property from the first JSON Object inside the data array
data[1].name // Will return the value of the `name` property from the second JSON Object inside the data array

How can I retrive a value from this json object?

<script>
var output = {"regions":{"4441":"Avtonomna Respublika Krym","4431":"Cherkas'ka Oblast'","4432":"Chernihivs'ka Oblast'","4433":"Chernivets'ka Oblast'","4434":"Dnipropetrovs'ka Oblast'","4435":"Donets'ka Oblast'","4436":"Ivano-Frankivs'ka Oblast'","4437":"Kharkivs'ka Oblast'","4438":"Khersons'ka Oblast'","4439":"Khmel'nyts'ka Oblast'","4440":"Kirovohrads'ka Oblast'","4443":"Kyyivs'ka Oblast'","4445":"L'vivs'ka Oblast'","4444":"Luhans'ka Oblast'","4442":"Misto Kyyiv","4450":"Misto Sevastopol","4446":"Mykolayivs'ka Oblast'","4447":"Odes'ka Oblast","4448":"Poltavs'ka Oblast'","4449":"Rivnens'ka Oblast'","4451":"Sums'ka Oblast'","4452":"Ternopil's'ka Oblast'","788":"Ukraine","4453":"Vinnyts'ka Oblast'","4454":"Volyns'ka Oblast'","4455":"Zakarpats'ka Oblast'","4456":"Zaporiz'ka Oblast'","4457":"Zhytomyrs'ka Oblast'"}}
alert(output.regions[1]);
</script>
This part gives me undefined:
alert(output.regions[1]);
How can I grab the first key/value pair for example. Basically I need to turn this into a select dropdown, the numeric keys would be the values and the names of the cities would be the option text.
Can iterate over it like:
for(key in output.regions) {
alert(key +' => '+output.regions[key]); // 4441 => Avtonomna Respublika Krym ...etc
}
Rather than a numeric index, you'll want to key into regions with the keys you've specified, like 4441, 4431, etc:
var output = {"regions":{"4441":"Avtonomna Respublika Krym","4431":"Cherkas'ka Oblast'","4432":"Chernihivs'ka Oblast'","4433":"Chernivets'ka Oblast'","4434":"Dnipropetrovs'ka Oblast'","4435":"Donets'ka Oblast'","4436":"Ivano-Frankivs'ka Oblast'","4437":"Kharkivs'ka Oblast'","4438":"Khersons'ka Oblast'","4439":"Khmel'nyts'ka Oblast'","4440":"Kirovohrads'ka Oblast'","4443":"Kyyivs'ka Oblast'","4445":"L'vivs'ka Oblast'","4444":"Luhans'ka Oblast'","4442":"Misto Kyyiv","4450":"Misto Sevastopol","4446":"Mykolayivs'ka Oblast'","4447":"Odes'ka Oblast","4448":"Poltavs'ka Oblast'","4449":"Rivnens'ka Oblast'","4451":"Sums'ka Oblast'","4452":"Ternopil's'ka Oblast'","788":"Ukraine","4453":"Vinnyts'ka Oblast'","4454":"Volyns'ka Oblast'","4455":"Zakarpats'ka Oblast'","4456":"Zaporiz'ka Oblast'","4457":"Zhytomyrs'ka Oblast'"}}
alert(output.regions[4441]); // alerts "Avtonomna Respublika Krym"
The regions entity is an object and not an array so you have to select its attribute by its associated key.
output.regions.4441
or
output.regions['4441']
The value with the key "regions" is a map, not an array - it has no ordering, therefore there is no concept of "first key/value pair" - you'll have to impose your own ordering if you want one.
This is because output.regions is an object, not an array. You would either need to access by the ID (778) or if you don't know it, than you can iterate to find it.
for (k in output.regions) { var key = k; break; }
alert(output.regions[key]);
There is no "first" value. Properties of javascript objects are not ordered. You can iterate over a javascript object like this:
for(key in output.regions){
alert(output.regions[key])
}
and check for the cycle of iteration, but there's no guarantee that the order won't change unexpectedly. To have a guaranteed order, you need to use an array.

Categories

Resources