undefined error while while accessing JSON data - javascript

$http({
method: 'GET',
// url: "https://na30.salesforce.com/services/data/v36.0/query?q=SELECT+id,+name,+Product2.Name,+Product2.Description,+Product2Id,+Pricebook2Id,+Product2.Family,+Product2.Product_Image_URL__c,+Product2.Product_Image__c,+Pricebook2.name+from+PricebookEntry+where+(Pricebook2.Id+=+'01s360000049JQh'+and+Product2.Family+=+'CURRIES')",
url: $scope.finalurl,
headers: { 'Content-Type': 'application/json' ,
'Authorization' : $scope.result1 }
}).success(function(response) {
$scope.result= response.totalSize;
// $scope.size = response.
// alert(" Products records captured");
// alert($scope.result);
var y =response.records;
alert(y);
localStorage.setItem("offlinecurries1",JSON.stringify(y));
var x =localStorage.getItem("offlinecurries1");
alert(JSON.stringify(x[0].Name));
getting undefined error in the above alert
my response data is
{
"totalSize": 497,
"done": true,
"records": [{
"attributes": {
"type": "PricebookEntry",
"url": "/services/data/v36.0/sobjects/PricebookEntry/01u36000001de83AAA"
},
"Id": "01u36000001de83AAA",
"Name": "P-0025",
"Pricebook2Id": "01s36000004AGVLAA4",
"Product2": {
"attributes": {
"type": "Product2",
"url": "/services/data/v36.0/sobjects/Product2/01t36000001To1lAAC"
},
"Product_Image_URL__c": null,
"Description": "ACHAPPAM175GMS X12PKT",
"Family": null,
"Product_Image__c": "<img src=\" \" alt=\"Not Avaialble\" height=\"50\" width=\"50\" border=\"0\"/>"
},
"Product2Id": "01t36000001To1lAAC",
"Pricebook2": {
"attributes": {
"type": "Pricebook2",
"url": "/services/data/v36.0/sobjects/Pricebook2/01s36000004AGVLAA4"
},
"Name": "UK Pricebook"
}
}, {
"attributes": {
"type": "PricebookEntry",
"url": "/services/data/v36.0/sobjects/PricebookEntry/01u36000001de84AAA"
},
"Id": "01u36000001de84AAA",
"Name": "P-0026",
"Pricebook2Id": "01s36000004AGVLAA4",
"Product2": {
"attributes": {
"type": "Product2",
"url": "/services/data/v36.0/sobjects/Product2/01t36000001To1mAAC"
},
"Product_Image_URL__c": null,
"Description": "ADA RICE 200 x 30",
"Family": null,
"Product_Image__c": "<img src=\" \" alt=\"Not Avaialble\" height=\"50\" width=\"50\" border=\"0\"/>"
},
"Product2Id": "01t36000001To1mAAC",
"Pricebook2": {
"attributes": {
"type": "Pricebook2",
"url": "/services/data/v36.0/sobjects/Pricebook2/01s36000004AGVLAA4"
},
"Name": "UK Pricebook"
}
}]
}

var x =localStorage.getItem("offlinecurries1");
this line returns a string!
you need to parse the string into a json object, add this line right after
var x =localStorage.getItem("offlinecurries1");
x = JSON.parse(x)

Try this. You need to strigify when saving and while retrieving you need to parse the json using JSON.parse so it can be converted back to array.
var json = { "totalSize": 497, "done": true, "records": [{ "attributes": { "type": "PricebookEntry", "url": "/services/data/v36.0/sobjects/PricebookEntry/01u36000001de83AAA" }, "Id": "01u36000001de83AAA", "Name": "P-0025", "Pricebook2Id": "01s36000004AGVLAA4", "Product2": { "attributes": { "type": "Product2", "url": "/services/data/v36.0/sobjects/Product2/01t36000001To1lAAC" }, "Product_Image_URL__c": null, "Description": "ACHAPPAM175GMS X12PKT", "Family": null, "Product_Image__c": "" }, "Product2Id": "01t36000001To1lAAC", "Pricebook2": { "attributes": { "type": "Pricebook2", "url": "/services/data/v36.0/sobjects/Pricebook2/01s36000004AGVLAA4" }, "Name": "UK Pricebook" } }, { "attributes": { "type": "PricebookEntry", "url": "/services/data/v36.0/sobjects/PricebookEntry/01u36000001de84AAA" }, "Id": "01u36000001de84AAA", "Name": "P-0026", "Pricebook2Id": "01s36000004AGVLAA4", "Product2": { "attributes": { "type": "Product2", "url": "/services/data/v36.0/sobjects/Product2/01t36000001To1mAAC" }, "Product_Image_URL__c": null, "Description": "ADA RICE 200 x 30", "Family": null, "Product_Image__c": "" }, "Product2Id": "01t36000001To1mAAC", "Pricebook2": { "attributes": { "type": "Pricebook2", "url": "/services/data/v36.0/sobjects/Pricebook2/01s36000004AGVLAA4" }, "Name": "UK Pricebook" } }] };
var y = json.records;
alert(y);
localStorage.setItem("offlinecurries1", JSON.stringify(y));
var x = JSON.parse(localStorage.getItem("offlinecurries1"));
alert(x[0].Name);

Related

How to print huge number of items from the json array

This is my json format with that im displaying my array items like this.
If i have more items in my array mean how can i print that all using for loop or is there any method available to print all that items in an array?
{
"workers": [
{ "id": "5001", "type": "Basic" },
{ "id": "5002", "type": "Admin" },
{ "id": "5003", "type": "Basic" }
],
"clients": [
{ "id": "5004", "type": "Pro" },
{ "id": "5005", "type": "Basic" },
{ "id": "5006", "type": "Basic" },
{ "id": "5007", "type": "Pro" }
]
}
<script>
const api_url = "API URL";
async function get_data_from_api() {
const response = await fetch(api_url);
var data = await response.json();
var track = data["workers"][2]["id"];
document.getElementById('demo2').innerHTML = track ;
}
</script>
Reference:
JSON.stringify()
const o = {
"workers": [
{ "id": "5001", "type": "Basic" },
{ "id": "5002", "type": "Admin" },
{ "id": "5003", "type": "Basic" }
],
"clients": [
{ "id": "5004", "type": "Pro" },
{ "id": "5005", "type": "Basic" },
{ "id": "5006", "type": "Basic" },
{ "id": "5007", "type": "Pro" }
]
};
output.innerHTML = JSON.stringify(o, undefined, 2);
<pre id="output"></pre>

Get a value from Nested JSON

I am completely new to Node.js. I have to read specific value from a API responded Nested JSON. I have tried to figure out but getting Undefined instead of the value. Whenever I am trying to read the base object I am getting the responded value but whenever I am trying to read the object under array then I am getting Undefined value.
Code Snippet:
var https = require('https');
var optionget = {
host: 'api-dev.dataoverflow.com',
port: 443,
path: '/test1/test2/',
method: 'GET',
HEADERS: {
'Authorization': 'Basic grege==',
'X-PruAppID : '
PlainCardPortal '
}
};
console.info(optionsget)
var reqGet = htttps.request(optionsget, function(res) {
console.log("statusCode: ", res.statusCode);
res.on('data', function(d) {
process.stdout.write(d);
process.stdout.write(jsonobj);
var Value = jsonobj.items.item.topping.type;
console.log(Value)
});
});
reqGet.end();
reqGet.on('error', function(e) {
console.error(e);
});
var optionsgetmsg = {
host: 'api-dev.dataoverflow.com',
port: 443,
method: 'GET'
};
console.info(optionsgetmsg);
var reqGet = https.request(optionsget, function(res) {
console.log("statusCode: ", res.statusCode);
res.setEncoding('utf-8')
res.on('data', function(data) {
process.stdout.write(data);
});
});
reqGet.end();
reqGet.on('error', function(e) {
console.error(e);
});
Nested JSON Snippet:
{
"items":
{
"item":
[
{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"batters":
{
"batter":
[
{ "id": "1001", "type": "Regular" },
{ "id": "1002", "type": "Chocolate" },
{ "id": "1003", "type": "Blueberry" },
{ "id": "1004", "type": "Devil's Food" }
]
},
"topping":
[
{ "id": "5001", "type": "None" },
{ "id": "5002", "type": "Glazed" },
{ "id": "5005", "type": "Sugar" },
{ "id": "5007", "type": "Powdered Sugar" },
{ "id": "5006", "type": "Chocolate with Sprinkles" },
{ "id": "5003", "type": "Chocolate" },
{ "id": "5004", "type": "Maple" }
]
},
...
]
}
}
I want to read type : Glazed from this JSON only but I am getting Undefined.
You have to iterate over the values in an array. You cannot access them using . notation. Use map to iterate over the array and get they types in the topping array
var jsonobj = {
"items": {
"item": [{
"id": "0001",
"type": "donut",
"name": "Cake",
"ppu": 0.55,
"batters": {
"batter": [{
"id": "1001",
"type": "Regular"
},
{
"id": "1002",
"type": "Chocolate"
},
{
"id": "1003",
"type": "Blueberry"
},
{
"id": "1004",
"type": "Devil's Food"
}
]
},
"topping": [{
"id": "5001",
"type": "None"
},
{
"id": "5002",
"type": "Glazed"
},
{
"id": "5005",
"type": "Sugar"
},
{
"id": "5007",
"type": "Powdered Sugar"
},
{
"id": "5006",
"type": "Chocolate with Sprinkles"
},
{
"id": "5003",
"type": "Chocolate"
},
{
"id": "5004",
"type": "Maple"
}
]
}
]
}
}
var Value = jsonobj.items.item.map(e=>e.topping)[0].map(x=>x.type);
console.log(...Value)

Need to get Name, Node Name and Phase Values from API

I am trying to get Name, Node Name and Phase values from JSON Data using JavaScript. Here is my JavaScript
<script>
$(document).ready(function () {
$.getJSON('http://ec2-3-82-117-70.compute-1.amazonaws.com:8080/api/v0/retrievePodStatus/default',
function (data) {
console.log(data)
document.body.append("Name: " + data.items[1].metadata.name);
// document.body.append(data.items[1].metadata.name);
// document.body.append(data.items[0].spec.nodeName);
});
});
</script>
I am just getting the name in here. Can someone please help me how to get Name, Node Name and Phase Values? find the below JSON as well.
"apiVersion": "v1",
"items": [
{
"apiVersion": "v1",
"kind": "Pod",
"metadata": {
"annotations": {
"kubernetes.io/limit-ranger": "LimitRanger plugin set: cpu request for container external-dns"
},
"creationTimestamp": "2019-02-28T16:22:49Z",
"generateName": "external-dns-5d69b66646-",
"labels": {
"app": "external-dns",
"pod-template-hash": "1825622202"
},
"name": "external-dns-5d69b66646-pmxmd",
"namespace": "default",
"ownerReferences": [
{
"apiVersion": "extensions/v1beta1",
"blockOwnerDeletion": true,
"controller": true,
"kind": "ReplicaSet",
"name": "external-dns-5d69b66646",
"uid": "170d9260-3b75-11e9-abe2-0ec5819342ce"
}
],
"resourceVersion": "2984",
"selfLink": "/api/v1/namespaces/default/pods/external-dns-5d69b66646-pmxmd",
"uid": "170e1a0d-3b75-11e9-abe2-0ec5819342ce"
},
"spec": {
"containers": [
{
"args": [
"--source=service",
"--source=ingress",
"--provider=aws",
"--registry=txt",
"--txt-owner-id=qpair"
],
"image": "registry.opensource.zalan.do/teapot/external-dns:v0.4.2",
"imagePullPolicy": "IfNotPresent",
"name": "external-dns",
"resources": {
"requests": {
"cpu": "100m"
}
},
"terminationMessagePath": "/dev/termination-log",
"terminationMessagePolicy": "File",
"volumeMounts": [
{
"mountPath": "/var/run/secrets/kubernetes.io/serviceaccount",
"name": "default-token-rr546",
"readOnly": true
}
]
}
],
"dnsPolicy": "ClusterFirst",
"nodeName": "ip-172-20-39-147.ec2.internal",
"restartPolicy": "Always",
"schedulerName": "default-scheduler",
"securityContext": {},
"serviceAccount": "default",
"serviceAccountName": "default",
"terminationGracePeriodSeconds": 30,
"tolerations": [
{
"effect": "NoExecute",
"key": "node.kubernetes.io/not-ready",
"operator": "Exists",
"tolerationSeconds": 300
},
{
"effect": "NoExecute",
"key": "node.kubernetes.io/unreachable",
"operator": "Exists",
"tolerationSeconds": 300
}
],
"volumes": [
{
"name": "default-token-rr546",
"secret": {
"defaultMode": 420,
"secretName": "default-token-rr546"
}
}
]
},
"status": {
"conditions": [
{
"lastProbeTime": null,
"lastTransitionTime": "2019-02-28T16:22:49Z",
"status": "True",
"type": "Initialized"
},
{
"lastProbeTime": null,
"lastTransitionTime": "2019-02-28T16:22:58Z",
"status": "True",
"type": "Ready"
},
{
"lastProbeTime": null,
"lastTransitionTime": "2019-02-28T16:22:49Z",
"status": "True",
"type": "PodScheduled"
}
],
"containerStatuses": [
{
"containerID": "docker://18b96317cf360d562fb3f849c6716c50a41a67a4dbc126164020531e1e4d84a9",
"image": "registry.opensource.zalan.do/teapot/external-dns:v0.4.2",
"imageID": "docker-pullable://registry.opensource.zalan.do/teapot/external-dns#sha256:d54b9eb8948b87eb7fcd938990ff2dbc9ca0a42d9c5d36fcaa75c7cf066f7995",
"lastState": {},
"name": "external-dns",
"ready": true,
"restartCount": 0,
"state": {
"running": {
"startedAt": "2019-02-28T16:22:57Z"
}
}
}
],
"hostIP": "172.20.39.147",
"phase": "Running",
"podIP": "100.96.7.3",
"qosClass": "Burstable",
"startTime": "2019-02-28T16:22:49Z"
}
},
I am just getting the name in here. Can someone please help me how to get Name, Node Name and Phase Values? find the below JSON as well.
Thanks, Much Appreciated
You were close with the code you posted. You just needed items[0] instead of items[1]. Remember the first element of an array is always 0. Other than that its as easy as checking the open and close brackets [] or {} to see where each nested object/array starts and ends.
Code:
var name = data.items[0].metadata.name
var nodeName = data.items[0].spec.nodeName
var phase = data.items[0].status.phase
snippet:
var data = {
"apiVersion": "v1",
"items": [{
"apiVersion": "v1",
"kind": "Pod",
"metadata": {
"annotations": {
"kubernetes.io/limit-ranger": "LimitRanger plugin set: cpu request for container external-dns"
},
"creationTimestamp": "2019-02-28T16:22:49Z",
"generateName": "external-dns-5d69b66646-",
"labels": {
"app": "external-dns",
"pod-template-hash": "1825622202"
},
"name": "external-dns-5d69b66646-pmxmd",
"namespace": "default",
"ownerReferences": [{
"apiVersion": "extensions/v1beta1",
"blockOwnerDeletion": true,
"controller": true,
"kind": "ReplicaSet",
"name": "external-dns-5d69b66646",
"uid": "170d9260-3b75-11e9-abe2-0ec5819342ce"
}],
"resourceVersion": "2984",
"selfLink": "/api/v1/namespaces/default/pods/external-dns-5d69b66646-pmxmd",
"uid": "170e1a0d-3b75-11e9-abe2-0ec5819342ce"
},
"spec": {
"containers": [{
"args": [
"--source=service",
"--source=ingress",
"--provider=aws",
"--registry=txt",
"--txt-owner-id=qpair"
],
"image": "registry.opensource.zalan.do/teapot/external-dns:v0.4.2",
"imagePullPolicy": "IfNotPresent",
"name": "external-dns",
"resources": {
"requests": {
"cpu": "100m"
}
},
"terminationMessagePath": "/dev/termination-log",
"terminationMessagePolicy": "File",
"volumeMounts": [{
"mountPath": "/var/run/secrets/kubernetes.io/serviceaccount",
"name": "default-token-rr546",
"readOnly": true
}]
}],
"dnsPolicy": "ClusterFirst",
"nodeName": "ip-172-20-39-147.ec2.internal",
"restartPolicy": "Always",
"schedulerName": "default-scheduler",
"securityContext": {},
"serviceAccount": "default",
"serviceAccountName": "default",
"terminationGracePeriodSeconds": 30,
"tolerations": [{
"effect": "NoExecute",
"key": "node.kubernetes.io/not-ready",
"operator": "Exists",
"tolerationSeconds": 300
},
{
"effect": "NoExecute",
"key": "node.kubernetes.io/unreachable",
"operator": "Exists",
"tolerationSeconds": 300
}
],
"volumes": [{
"name": "default-token-rr546",
"secret": {
"defaultMode": 420,
"secretName": "default-token-rr546"
}
}]
},
"status": {
"conditions": [{
"lastProbeTime": null,
"lastTransitionTime": "2019-02-28T16:22:49Z",
"status": "True",
"type": "Initialized"
},
{
"lastProbeTime": null,
"lastTransitionTime": "2019-02-28T16:22:58Z",
"status": "True",
"type": "Ready"
},
{
"lastProbeTime": null,
"lastTransitionTime": "2019-02-28T16:22:49Z",
"status": "True",
"type": "PodScheduled"
}
],
"containerStatuses": [{
"containerID": "docker://18b96317cf360d562fb3f849c6716c50a41a67a4dbc126164020531e1e4d84a9",
"image": "registry.opensource.zalan.do/teapot/external-dns:v0.4.2",
"imageID": "docker-pullable://registry.opensource.zalan.do/teapot/external-dns#sha256:d54b9eb8948b87eb7fcd938990ff2dbc9ca0a42d9c5d36fcaa75c7cf066f7995",
"lastState": {},
"name": "external-dns",
"ready": true,
"restartCount": 0,
"state": {
"running": {
"startedAt": "2019-02-28T16:22:57Z"
}
}
}],
"hostIP": "172.20.39.147",
"phase": "Running",
"podIP": "100.96.7.3",
"qosClass": "Burstable",
"startTime": "2019-02-28T16:22:49Z"
}
}],
}
var name = data.items[0].metadata.name
var nodeName = data.items[0].spec.nodeName
var phase = data.items[0].status.phase
console.log(name)
console.log(nodeName)
console.log(phase)

Why data is doubled, how I can fix it?

Good afternoon.
I have required json, which contains the basic template for the layout of Adaptive Cards (bot framework).
Here's this json:
{
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
"version": "1.0",
"type": "AdaptiveCard",
"speak": "",
"body": [
{
"type": "TextBlock",
"horizontalAlignment": "center",
"text": "Все машины",
"weight": "bolder",
"isSubtle": false
},
{
"type": "TextBlock",
"text": "Внимание, вы вошли в режим тендера.",
"separator": true
}
],
"actions": [
{
"type": "Action.Submit",
"title": "Подтвердить лот(ы)",
"data": {
"msteams": {
"type": "messageBack",
"displayText": "Идет подтверждение ваших лотов, ожидайте!",
"text": "/accept",
"value": "{\"x\": \"bfVal\", \"y\": \"from value\"}"
}
}
},
{
"type": "Action.Submit",
"title": "Отменить все лоты",
"data": {
"x": "123",
"msteams": {
"type": "messageBack",
"displayText": "Идет отменение ваших лотов, ожидайте!",
"text": "/cancel",
"value": "{\"bfKey\": \"bfVal\", \"conflictKey\": \"from value\"}"
}
}
}
]
}
I also have a loop that takes data from my source and forms another json from it.
try {
// Pull in the data from Microsoft Graph.
const client = new SimpleGraphClient(tokenResponse.token);
const me = await client.getList();
var i = 0;
while (i < me['value'].length) {
feed = {
"type": "ColumnSet",
"separator": true,
"columns": [
{
"type": "Column",
"width": 1,
"items": [
{
"type": "TextBlock",
"text": "Продукт",
"isSubtle": true
},
{
"type": "TextBlock",
"size": "extraLarge",
"color": "accent",
"text": me.value[i].fields.Good,
"spacing": "none"
},
{
"type": "TextBlock",
"text": "Дата: " + dateFormat(me.value[i].fields.ShipmentDateTime, 'dd-mm-yyyy'),
"spacing": "yes"
}
]
},
{
"type": "Column",
"width": "auto",
"items": [
{
"type": "TextBlock",
"text": " "
},
{
"type": "Image",
"url": "https://png.pngtree.com/svg/20170614/engine_oil_410031.png",
"size": "medium",
"spacing": "yes"
},
{
"type": "TextBlock",
"text": " ID: " + me.value[i].fields.id,
"value": me.value[i].fields.id
}
]
},
{
"type": "Column",
"width": 1,
"items": [
{
"type": "TextBlock",
"horizontalAlignment": "right",
"text": "RUB",
"isSubtle": true
},
{
"type": "TextBlock",
"horizontalAlignment": "right",
"size": "extraLarge",
"color": "accent",
"text": me.value[i].fields.PricePerTon,
"spacing": "none"
},
{
"type": "Input.Toggle",
"title": "Приобрести лот",
"valueOn": "true",
"valueOff": "false",
"id": "buyGood",
"spacing": "yes"
}
]
}
]
}
tender.body.push(feed);
i++;
}
Then I combine these json.
This works well, but when you retrieve the data again, the data is doubled.
How can this be resolved?
Thanks in advance.
It looks like every time you create a new card, you are appending the JSON object you created in the while loop to your required JSON object. Consequently, the next time you try to create a new card, the data from the previous request is still stored in your required JSON object. To avoid this, create a copy of the required JSON Object and store it in a different variable before your while loop. You can use JSON.parse(JSON.stringify(obj)) to create a copy of a JSON Object.
Your code should look something like this:
// create a copy of the required JSON Object
// and store it in a new variable
const card = JSON.parse(JSON.stringify(tender));
var i = 0;
while (i < me['value'].length) {
let feed = {
"type": "ColumnSet",
"separator": true,
...
}
// push feed to `card` instead of `tender`
card.body.push(feed);
i++;
}
...
// send `card` to user instead of `tender`
await turnContext.sendActivity({
text: "Double Data Card",
attachments: [CardFactory.adaptiveCard(card)]
});

Facebook Open Graph not returning all results for Books.Read?

When using the Facebook Open Graph explorer, I run the following, to get a list of my books read.
/706685881/books.reads?limit=25&offset=0
This returns only 5 results, even though I have more books read than that, and I've explicitly requested up to 25 results. Following the paging link to the (theoretical) more results, shows a page with no more results.
here's my output of the query:
{
"data": [
{
"data": {
"book": {
"id": "452418224806835",
"url": "https://www.facebook.com/pages/Fantastic-Voyage/452418224806835",
"type": "books.book",
"title": "Fantastic Voyage"
}
},
"id": "10151871872740882"
},
{
"data": {
"book": {
"id": "106151566083577",
"url": "https://www.facebook.com/pages/The-Andromeda-Strain/106151566083577",
"type": "books.book",
"title": "The Andromeda Strain"
}
},
"id": "10151870390740882"
},
{
"data": {
"progress": [
{
"timestamp": 1388668020,
"percent_complete": 0
},
{
"timestamp": 1392949225,
"percent_complete": 100
}
],
"book": {
"id": "10150233066083545",
"url": "http://www.goodreads.com/book/show/10664113-a-dance-with-dragons",
"type": "good_reads:book",
"title": "A Dance with Dragons (A Song of Ice and Fire, #5)"
}
},
"id": "10151867499170882"
},
{
"data": {
"progress": [
{
"timestamp": 1391350736,
"percent_complete": 0
},
{
"timestamp": 1392569208,
"percent_complete": 100
}
],
"book": {
"id": "1390736374489290",
"url": "http://www.goodreads.com/book/show/18405477-city-of-the-sun",
"type": "good_reads:book",
"title": "City of the Sun"
}
},
"id": "10151860185710882"
},
{
"data": {
"book": {
"id": "526531387368738",
"url": "http://apps.facebook.com/bookscout/?currworkid=9000000000133742",
"type": "books.book",
"title": "Gates of Fire"
}
},
"id": "10151226827780882"
}
],
"paging": {
"next": "https://graph.facebook.com/706685881/books.reads?fields=data&limit=25&offset=25&__after_id=10151226827780882"
}
}
Anybody seeing what I am doing wrong?

Categories

Resources