Accessing json elements gives undefined error - javascript

I have the following JSON:
{
"list": {
"q": "raw",
"sr": "28",
"ds": "Standard Reference",
"start": 0,
"end": 1,
"total": 1391,
"group": "",
"sort": "n",
"item": [
{
"offset": 0,
"group": "Poultry Products",
"name": "Chicken, broilers or fryers, dark meat, thigh, meat only, raw",
"ndbno": "05096",
"ds": "SR"
}
]
}
}
But when I try to access elements in this json i keep getting undefined error... I already checked if the JSON is valid and yes the json is valid!
Maybe I am accesing the JSON wrong? The JSON is stored in a variable called result. This is how I tried so far:
console.log(result.list.ds);
I also tried:
console.log(result["0"].list.ds);
but both solutions give me the following error:
Uncaught TypeError: Cannot read property 'ds' of undefined
Why is this happening? Any tips or suggestions are welcome!

Is your JSON stored in your variable as a string? Try:
console.log(JSON.parse(result).list.ds)
The reason I ask is that the text Uncaught TypeError: Cannot read property 'ds' of undefined tells me that your result variable does not have a list property, which your JSON clearly would if it were an object, but it most assuredly would not if you had accidentally forgotten to parse your JSON string.

Your JSON is valid and if you are accessing the ds property inside list object. Your syntax console.log(result.list.ds); is correct.
But, If you are trying to access the ds property inside the item array then you have to iterate the array to get the ds property.
DEMO
var result = {
"list": {
"q": "raw",
"sr": "28",
"ds": "Standard Reference",
"start": 0,
"end": 1,
"total": 1391,
"group": "",
"sort": "n",
"item": [{
"offset": 0,
"group": "Poultry Products",
"name": "Chicken, broilers or fryers, dark meat, thigh, meat only, raw",
"ndbno": "05096",
"ds": "SR"
}]
}
};
var res = result.list.item.map(function(elem) {
return elem.ds;
})
console.log(res);

Related

Microsoft power automate: JSON "Object reference not set to an instance of an object"

I am attempting to create a JSON Object from an array to pass into a Microsoft product. The format in which the JSON object is accepted is shown beneath (content-type: "application/json"):
{
"value": [
{
"activityGroupNames": [],
"confidence": 0,
"description": "This is a canary indicator for demo purpose. Take no action on any observables set in this indicator.",
"expirationDateTime": "2019-03-01T21:44:03.1668987+00:00",
"externalId": "Test--8586509942423126760MS164-0",
"fileHashType": "sha256",
"fileHashValue": "b555c45c5b1b01304217e72118d6ca1b14b7013644a078273cea27bbdc1cf9d6",
"killChain": [],
"malwareFamilyNames": [],
"severity": 0,
"tags": [],
"targetProduct": "Azure Sentinel",
"threatType": "WatchList",
"tlpLevel": "green",
},
{
"activityGroupNames": [],
"confidence": 0,
"description": "This is a canary indicator for demo purpose. Take no action on any observables set in this indicator.",
"expirationDateTime": "2019-03-01T21:44:03.1748779+00:00",
"externalId": "Test--8586509942423126760MS164-1",
"fileHashType": "sha256",
"fileHashValue": "1796b433950990b28d6a22456c9d2b58ced1bdfcdf5f16f7e39d6b9bdca4213b",
"killChain": [],
"malwareFamilyNames": [],
"severity": 0,
"tags": [],
"targetProduct": "Azure Sentinel",
"threatType": "WatchList",
"tlpLevel": "green",
}
]
}
I making use of an inline code script in Microsoft automate that performs the following in JavaScript:
var threat = workflowContext.actions.Compose.outputs;
var value = Object.values(threat);
return value;
The workflowContext.actions.Compose.outputs line pulls an array consisting of objects shown in the following snippet:
[{"id": "1", "activityGroupNames": "test2"}, {"id": "2", "activityGroupNames": "test3"}, {"id": "3", "activityGroupNames": "test4"}]
This is my output:
{
"body": [
{
"id": "1",
"action": "alert",
"activityGroupNames": "test2"
},
{
"id": "2",
"action": "alert",
"activityGroupNames": "test3"
},
{
"id": "3",
"action": "alert",
"activityGroupNames": "test2"
}
]
}
it is pretty much identical to the format described my Microsoft shown in the first snippet. (https://learn.microsoft.com/en-us/graph/api/tiindicator-submittiindicators?view=graph-rest-beta&tabs=http) at the bottom.
I am unsure as to how I can change the key name from "body" to "value" and think maybe this will resolve my issue. Either way, I'd appreciate any other help on the matter, if any more context is required, please ask.
EDIT: The image beneath shows that the returned return value; is in fact being used as the input for a POST request to the Microsoft graph API

Losing values from redux object when spreading into new object

I'm fetching data from redux store with useSelector.
const customerProduct = useSelector((state) => state.objects.customersProducts[match.params.customerProductId]);
If I log the data it is displayed like this in the console:
Once I try to use spread operator to create a new object, it would lose all the values with (...).
Like this:
const updatedCustomerProduct = { ...customerProduct, newValue: "abc" };
I would get an output like this:
const uptdatedCustomerProduct =
{
"id": "AALzgGxtlg",
"_objCount": 6360,
"newValue": "abc",
"className": "customerOfferMetadata"
}
What's going on here? How could I handle these values? If I copy the object from the console the object is perfectly visible.
Even in redux dev tools the data is displayed like this:
{
"entityInfo": {
"productId": 441,
"bundleOfferId": 22
},
"title": {
"us": "Special Offer"
},
"desc": {
"us": "6 months"
},
"order": 0,
"enabled": true,
"entityType": "product",
"detailsUrl": "www.google.com",
"thumb": {
"__type": "Pointer",
"className": "Resource",
"objectId": "12345"
},
"createdAt": "2021-02-26T18:48:25.358Z",
"updatedAt": "2021-09-21T21:41:49.384Z",
"clientId": 1,
"objectId": "AALzgGxtlg"
}
I'm not sure what code is generating those objects for you, but when you see properties in the console that are semitransparent, they are non-enumerable. This means that when applying the spread operator, they are not iterated over, and hence they do not make it into the new object.
To make all properties enumerable, check out the question Make all properties enumerable.

How do I get the contents of a JSON file with JSON inside of the array

I would like some help getting the contents of the JSON file, as the "games" array has JSON inside of it.
Here's the JSON file.
"games": [
{
"creatorId": 3642592,
"creatorName": "Schwifty Studios",
"creatorType": "Group",
"totalUpVotes": 1263723,
"totalDownVotes": 273834,
"universeId": 498490399,
"name": "Mad City",
"placeId": 1224212277,
"playerCount": 8386,
"imageToken": "T_1224212277_e312",
"isSponsored": false,
"nativeAdData": "",
"isShowSponsoredLabel": false,
"price": null,
"analyticsIdentifier": null,
"gameDescription": null
},
{
"creatorId": 708786490,
"creatorName": "lord_faker08",
"creatorType": "User",
"totalUpVotes": 454,
"totalDownVotes": 1661,
"universeId": 1274534437,
"name": "Mad City Mad City Mad City Mad City Mad City Mad C",
"placeId": 3646141738,
"playerCount": 5,
"imageToken": "T_3646141738_ffb3",
"isSponsored": false,
"nativeAdData": "",
"isShowSponsoredLabel": false,
"price": null,
"analyticsIdentifier": null,
"gameDescription": null
}
]
I actually tried to get the contents using the number so I could get the data,
games.1.name
but it didn't work.
Use games[1].name. It's the common syntax of accessing object x in an array.
With games.1.name you are basically telling the compiler to access the games variable, get the 1 property of the object and get the name property of the games.1 object.

Passing JSON created in PHP to Javascript changes a result and I don't understand why

I have an object in PHP that I'm passing to Javascript in the same page. It seems to be passing through fine as a console.log statement returns the expected result but when I try to turn it into a Javascript variable the "id" is replaced with a 1, no quotation marks, rather than the expected result. If I wrap the PHP statement in the Javascript in square brackets the "id" does not change, but then it's formatted oddly. What I'm wondering is why this is occurring and if there's something I should do differently.
ETA:
Since there was some confusion:
The input is "Data," below. That is generated from the results of a SQL query by way of an array_push statement. I have included the code for each row of the SQL query and the array_push statement below, but there does not seem to be a problem with the PHP side.
My expected output is simply the data to be transferred to a JSON object on the javascript side with the appropriate variable, using the code mentioned under "Javascript." Instead I am getting something like this as console.log output:
{
DNB_number: "0"
color: "darkred"
id: 1
name: "Anonymous"
role: "Author"
size: null
type: "person"
witness_work_id: "1467"
witness_work_role_id: "1659"
}
That 1 under id is what is the issue.
There is nothing happening on the javascript side before the attempt to convert the result to a javascript variable (what you see under javascript below), so there's not much else I can tell you there. The conversion on the PHP side happens, I start my javascript, then immediately attempt to invoke it on the javascript side.
PHP code:
$person_color = "darkred";
foreach ($person_data as $row) {
$person_id = $row["person_id"];
$type = "person";
$witness_work_role_id = $row["Witness_work_role_id"];
$witness_work_id = $row["Witness_work_id"];
$person = $row["Person_name"];
$DNB = $row["Oxford_DNB_number"];
$role = $row["Role"];
$color = $person_color;
array_push($GLOBALS['person_array'], array(
'id'=>$person_id,
'witness_work_role_id'=>$witness_work_role_id,
'witness_work_id'=>$witness_work_id,
'type'=>$type,
'name'=>$person,
'DNB_number'=>$DNB,
'role'=>$role,
'color'=>$color,
'size'=> NULL
));
}
$jperson = json_encode($person_array);
Javascript code:
person_array = <?=$jperson; ?>;
Data:
[
{
"id": "1",
"witness_work_role_id": "1660",
"witness_work_id": "1468",
"type": "person",
"name": "Anonymous",
"DNB_number": "0",
"role": "Author",
"color": "darkred",
"size": null
},
{
"id": "152",
"witness_work_role_id": "1573",
"witness_work_id": "1384",
"type": "person",
"name": "Gilbert Banester",
"DNB_number": "0",
"role": "Author",
"color": "darkred",
"size": null
},
{
"id": "153",
"witness_work_role_id": "1574",
"witness_work_id": "1385",
"type": "person",
"name": "Elizabeth Plantagenet (Elizabeth of York)",
"DNB_number": "8635",
"role": "Author",
"color": "darkred",
"size": null
},
{
"id": "3",
"witness_work_role_id": "1642",
"witness_work_id": "1451",
"type": "person",
"name": "Geoffrey Chaucer",
"DNB_number": "5191",
"role": "Author",
"color": "darkred",
"size": null
},
{
"id": "7",
"witness_work_role_id": "1643",
"witness_work_id": "975",
"type": "person",
"name": "Benedict Burgh",
"DNB_number": "3390",
"role": "Author",
"color": "darkred",
"size": null
},
{
"id": "5",
"witness_work_role_id": "1659",
"witness_work_id": "1467",
"type": "person",
"name": "Anonymous",
"DNB_number": "0",
"role": "Author",
"color": "darkred",
"size": null
}
]
Let's work this out in a minimal example. Based on what you're saying, the variable is a string (of an int), and the value is correct in memory. But when you view that value via console.log you see an int instead of a string.
var test = "1";
if (typeof test == 'string') {
console.log('yes, it is a string');
} else {
console.log('no, it is not a string');
}
If you copy/paste the above into your JS console and run it, you'll see the message yes, it is a string. This proves that it is a string in memory.
another way to test this value is to just run test in your console, and you should see "1" output.
But now, when we use console.log to inspect the value:
console.log(test) outputs 1
Another example without a variable: console.log("123") outputs 123, not "123"
What's apparently happening is just an artifact of console.log. See Javascript console.log(object) vs. concatenating string for more examples and explanations. https://dmitripavlutin.com/console-log-tips/ lists some more options. For instance, if you create an object containing your variable and output that: console.log({test}) will output {test: "1"}, so you can see again that test is a string with the value "1".

Differences with API's when trying to pull data

I am having difficulty with a pulling some data from an API for a school project using Jquery.
If I use the following coinmaketcap API I get the following response
https://api.coinmarketcap.com/v1/ticker/bitcoin/
[
{
"id": "bitcoin",
"name": "Bitcoin",
"symbol": "BTC",
"rank": "1",
"price_usd": "8854.92",
"price_btc": "1.0",
"24h_volume_usd": "6759730000.0",
"market_cap_usd": "150480289107",
"available_supply": "16993975.0",
"total_supply": "16993975.0",
"max_supply": "21000000.0",
"percent_change_1h": "-0.13",
"percent_change_24h": "0.12",
"percent_change_7d": "8.3",
"last_updated": "1524459272"
}
]
I get am able to get the symbol for Bitcoin and place it into a variable by using this code
> $.getJSON('https://api.coinmarketcap.com/v1/ticker/btc/',
> function(data){
> var symbol = (data[0].symbol)
> })
Once I have it I can place it in a div.
However when I use cryptocompare API I don't get anything back
https://min-api.cryptocompare.com/data/coin/generalinfo?fsyms=BTC,&tsym=USD
$.getJSON('https://min-api.cryptocompare.com/data/coin/generalinfo?fsyms=BTC&tsym=USD', function(data){
var symbol = (data[0].Internal)
});
This is the response -
{
"Message": "Success",
"Type": 100,
"Data": [
{
"CoinInfo": {
"Id": "1182",
"Name": "BTC",
"FullName": "Bitcoin",
"Internal": "BTC",
"ImageUrl": "/media/19633/btc.png",
"Url": "/coins/btc/overview",
"Algorithm": "SHA256",
"ProofType": "PoW",
"NetHashesPerSecond": 27483320229.3688,
"BlockNumber": 518932,
"BlockTime": 600,
"BlockReward": 12.5,
"Type": 1,
"DocumentType": "Webpagecoinp"
},
"ConversionInfo": {
"Conversion": "direct",
"ConversionSymbol": "",
"CurrencyFrom": "BTC",
"CurrencyTo": "USD",
"Market": "CCCAGG",
"Supply": 16986575,
"TotalVolume24H": 380849.0498955779,
"SubBase": "5~",
"SubsNeeded": [
"5~CCCAGG~BTC~USD"
],
"RAW": [
"5~CCCAGG~BTC~USD~4~8875.23~1524460635~0.00477012~42.152119404000004~231254719~10820.885574747872~96327075.76938197~66326.58563159907~593473019.8524572~8823.46~8917.05~8804.2~8864.31~9065~8780.91~Bitfinex~7ffe9"
]
}
}
]
}
Why is the second piece of code not working? Please help!
The second API is returning an object (in JSON format), not an array - see how the first character is { and how it has keys and values? You need to access the appropriate property to get the value you want. [0] notation indicates you're trying to access the first element of the array, but the outer object is not an array in this situation.
$.getJSON('https://min-api.cryptocompare.com/data/coin/generalinfo?fsyms=BTC&tsym=USD',
function(data){
var symbol = data.Data[0].CoinInfo.Internal;
});
In both the cases, we are getting data in different form. So, To get the 'BTC' in variable .
for 1st case -> symbol = data[0] ['symbol']
for 2nd case -> symbol = data['Data'][0]['CoinInfo']['Internal']
one is an [array of JSON] while other is an [object having key 'Data' with array value].

Categories