json.stringify(obj) error obj is not defined - javascript

I'm trying to access an element of an object but whenever I do the code throws an undefined error.
var pokeShow= function(pokaName,datapp) {
for(var i=0;i<datapp.pokemon.length;i++) {
if(datapp.pokemon[i].name==pokaName){
var dispo=datapp.stringify(pokemon[i]) // this line is showing error that pokemon is not defined
alert(dispo)
}
else
alert("wrong input")
}
the json file(a block of it):-
var pokeData = {
"pokemon": [{
"id": 1,
"num": "001",
"name": "Bulbasaur",
"img": "http://www.serebii.net/pokemongo/pokemon/001.png",
"type": [
"Grass",
"Poison" ...
Pokemon seems to be clearly defined in the object, why is this error being thrown?

It seems you are trying to get part of an object that you haven't defined as it's own.
datapp.pokemon[i].name==pokaName
pokemon[i]
Try replacing
var dispo=datapp.stringify(pokemon[i])
with
var dispo=datapp.stringify(datapp.pokemon[i])
Also, I am not entirely sure but I think you meant to put JSON.stringify instead of datapp.stringify

for(var i=0;i<datapp.pokemon.length;i++) {
if(datapp.pokemon[i].name==pokaName){
var dispo=datapp.stringify(pokemon[i])
alert(dispo)
}
}
pokemon is an array which is part of datapp, which you're doing right when you're comparing if(datapp.pokemon[i].name==pokaName). The problem is when you stringify it, you're not referring to datapp.pokemon[i] and hence the undefined. Instead you can change it to below
var dispo=JSON.stringify(datapp.pokemon[i])

Related

Get object value that has numeric key in react native

I getting data as object like below:
{
"Version": "AAA",
"Schema" : "AAA",
"Total" : 432234,
....
"Content": {
"1" : {
"1" : {
...
},
"2" : {
...
},
...
}
}
}
How can I get the values from the numeric key in react native?
something like this:
var first_numeric_key = 1;
var second_numeric_key = 2;
aboveObject.Content[first_numeric_key][second_numeric_key];
I tried with the below script but still getting issues.
aboveObject.Content["1"]
TypeError: undefined is not an object (evaluating '_this4.state.contents.content["1"])
What is the best approach for this?
I am not a React Native guy but this seems more like a JavaScript syntax nuance.
You can access object keys as obj['key']
Here, in your case, it will be
aboveObject.Content['1']['2']
Updating answer after OP's edit to the question
const first_numeric_key = 1;
const second_numeric_key = 2;
aboveObject.Content[first_numeric_key.toString()][second_numeric_key.toString()];
EDIT
This is working without convert to the string
aboveObject.Content[first_numeric_key][second_numeric_key]
The issue was the exception handling, since there was some delaying when the app get the data from the fetch() function so the aboveObject was null at the very first time.

Convert JSON to HTML: Uncaught TypeError: json.forEach is not a function

I want to convert JSON to HTML to display it on website. I've googled, and this error occurs when when json is a string, and first I need to parse. But when I use JSON.parse, the console says it is already an object (Unexpected token o in JSON at position 1).
$(document).ready(function() {
$("#getMessage").on("click", function() {  
$.getJSON("http://quotes.rest/qod.json", function(json) {
var html = "";
json.forEach(function(val) {
var keys = Object.keys(val);
html += "<div class = 'blabla'>";
keys.forEach(function(key) {
html += "<b>" + key + "</b>: " + val[key] + "<br>";
});
html += "</div><br>";
});
$(".message").html(html);
});
});
});
json is an object, not an array. You can use forEach only on arrays.
As you have done already, you can iterate over the object's keys like this:
Object.keys(json).forEach(function(key) {
var value = json[key];
...
});
In addition to what everyone else said, it appears that the JSON response does not look like you think it does.
var json = {
"success": {
"total": 1
},
"contents": {
"quotes": [{
"quote": "It's not whether you get knocked down, it...s whether you get up.",
"length": "65",
"author": "Vince Lombardi",
"tags": [
"failure",
"inspire",
"learning-from-failure"
],
"category": "inspire",
"date": "2016-08-09",
"title": "Inspiring Quote of the day",
"background": "https://theysaidso.com/img/bgs/man_on_the_mountain.jpg",
"id": "06Qdox8w6U3U1CGlLqRwFAeF"
}]
}
};
var messageEl = document.querySelector('.message');
messageEl.innerText = json.contents.quotes[0].quote;
<div class="message"></div>
$.getJson already transforms a JSON object into a javascript object, so you would not need to parse it again.
However, your problem starts with forEach, which is an Array method, not an Object method, therefor it will not work in your use case.
var jsonKeys = Object.keys(json); jsonKeys.forEach(...) will work, as Object.keys returns an array of Object keys.

Accessing objects from within object?

This is probably a very newbish question, but I am learning javascript and working with pouchDB. I have a search function that returns something like:
{"total_rows":1,"rows":[{"id":"mydoc","score":0.7071067811865475,"doc":{"title":"Guess who?","text":"It's-a me, Mario!","_id":"mydoc","_rev":"1-21bd9b0c99791947618e98a23134b312"},"highlighting":{"text":"It's-a me, Mario!"}}]}
I can access the total_rows value easily obviously, but how would I access the value of 'text'?
Simply with x.rows[0].doc.text.
Edit: To help you understand a little better what's happening here, you're accessing "sub children" with the . operator. We're asking for the rows array inside x and then specifying we want the first row (remember that arrays are 0-indexed, meaning the first element in an array is at position 0).
From there, we just access the doc child, and the text attribute it contains.
var obj = {"total_rows":1,"rows":[{"id":"mydoc","score":0.7071067811865475,"doc":{"title":"Guess who?","text":"It's-a me, Mario!","_id":"mydoc","_rev":"1-21bd9b0c99791947618e98a23134b312"},"highlighting":{"text":"It's-a me, Mario!"}}]};
console.log(obj.rows[0].doc.text);
Hi please cchecck this
var abc = {
"total_rows": 1,
"rows": [
{
"id": "mydoc",
"score": 0.7071067811865475,
"doc": {
"title": "Guess who?",
"text": "It's-a me, Mario!",
"_id": "mydoc",
"_rev": "1-21bd9b0c99791947618e98a23134b312"
},
"highlighting": {
"text": "It's-a me, Mario!"
}
}
]
}
console.log(abc.rows[0].doc.text);
console.log(abc.rows[0].highlighting.text);
it is better to identify each row by using 'id' to parse javascript object.
try this (javascript es6)
const obj = {"total_rows":1,"rows":[{"id":"mydoc","score":0.7071067811865475,"doc":{"title":"Guess who?","text":"It's-a me, Mario!","_id":"mydoc","_rev":"1-21bd9b0c99791947618e98a23134b312"},"highlighting":{"text":"It's-a me, Mario!"}}]}
const id = 'mydoc'
const text = obj.rows.find(item => item.id === id).doc.text
console.log(text)
javascript es5 or previous version
var obj = {"total_rows":1,"rows":[{"id":"mydoc","score":0.7071067811865475,"doc":{"title":"Guess who?","text":"It's-a me, Mario!","_id":"mydoc","_rev":"1-21bd9b0c99791947618e98a23134b312"},"highlighting":{"text":"It's-a me, Mario!"}}]};
var id = 'mydoc';
var text = obj.rows.find(function(item) { return item.id === id; }).doc.text;
console.log(text);

How to extract data from this JSON string?

I'm new to JSON and Jquery, and I can't find how to extract the values of ProjectCode from this JSON string.
[
{
"ProjectID": 3,
"CLustomerCode": "XYZ001",
"ProjectCode": "YZPROJ1",
"Description": "Project1",
"IssueManager": "iant",
"NotificationToggle": false,
"ProjectStatus": null,
"Added": "/Date(1400701295853}/",
"Added By": "iant",
"Changed": "/Date(1400701295853)/",
"Changed By": "iant"
},
{
"ProjectID": 4,
"CustomerCode": "XYZ001",
"ProjectCode": "XYXPROJ2",
"Description": "Projecton:Project2",
"IssweManager": "iant",
"NotificationToggle": false,
"Projectstatus": null,
"Added": "lDate(1400701317980)/",
"AddedBy": "iant",
"Changed": "/Date(1400701317980)/",
"Changed By": "iant"
}
]
The string above is from a variable called data that is the return value from stringify. I expected to be able to do something like
string proj = data[i].ProjectCode;
but intellisense doesn't include any of the properties.
I know very little about JSON - any help appreciated.
Thanks for reading.
Use parseJSON:
var obj = jQuery.parseJSON("{ 'name': 'Radiator' }");
alert(obj.name);
You need to loop through each object returned in the response and get the ProjectCode property inside each one. Assuming the data variable is your JSON this should work:
$.each(data, function(i, obj) {
console.log(obj.ProjectCode);
});
Use JSON.parse():
var a; // Your JSON string
var b = JSON.parse(a); //Your new JSON object
//You can access Project code, use index i in b[i].ProjectCode in a loop
var projectCode = b[0].ProjectCode;
You should post the raw code so its easier to visualize this stuff. Since what you are looking for is the list of ProjectCodes (in this case - ["XYZPROJ1", "XYZPROJ2"]).
It seems like what we have is an array or list ([...]) of projects. Where each project has a ProjectID, CustomerCode, ProjectCode, Description and so on...
So lets assume data points at this JSON blob. Here is how you would go about accessing the ProjectCode:
// Access the "i"th project code
var p_i_code = data[i].ProjectCode;
// How many projects?
var num_projects = data.length; // since data is a list of projects
// Want the list of project codes back? (I use underscore.js)
var project_codes = _.map(data, function(project) {
return project.ProjectCode;
});

Using variable keys to access values in JavaScript objects

The code:
function updateDashboardData() {
$.getJSON("includes/system/ajaxDataInterface.php", {recordcount:1}, function(data) {
$('.stationContainer').each(function(data) {
var bsID = $(this).attr("id");
var bsStatus = $(this).children('.stationStatus');
alert(data[bsID][0].time);
bsStatus.find('.bs_maxHandsets').text(data[bsID][0].maxHandsets);
bsStatus.find('.bs_time').text(data[bsID][0].time);
});
});
}
The object data:
{
"A5A50000": [{
"bsid": "A5A50000",
"chanCount": 17,
"time": "2009-05-27 16:36:45",
"avgInterference": 1.711765,
"maxInterference": 4.97,
"avgHandsets": 205.1176,
"maxHandsets": 315,
"avgCalls": 6.4118,
"maxCalls": 13,
"avgCBA": 3868.98059,
"maxCBA": 7463,
"sumSuccessCBA": 197318,
"sumTimeoutHandoff": 133,
"sumAttemptHandoff": 1028,
"sumDeniedHandoff": 216,
"sumConfirmHandoff": 679,
"sumHandoffNetwork": 61873,
"sumJoinNetwork": 96888,
"sumLeaveNetwork": 93754,
"sumRcvdKeepalive": 98773,
"sumTimeoutKeepalive": 19748,
"sumAttemptUplink": 93689,
"sumBlockedUplink": 62453
}]
}
The problem:
alert(data.A5A50000[0].time); properly displays "2009-05-27 16:36:45".
alert(bsID); properly displays "A5A50000".
alert(data.bsID[0].time); reports "data.bsID is undefined".
alert(data[bsID][0].time); reports "data[bsID] is undefined".
I'm a little unclear when a variable is/isn't evaluated. Maybe I'm overlooking something silly, but I can't figure out my problem here.
You can access object properties by dot notation or by bracket notation.
var x = {'test': 'hi'};
alert(x.test); // alerts hi
alert(x['test']); // alerts hi
When you have a dynamic value, you have to use the latter:
var property = 'test';
alert(x.property); // looks for x.property, undefined if it doesn't exist
alert(x[property]); // looks for x['test'], alerts hi
So what you actually want is:
alert(data[bsID][0].time);
EDIT:
Not sure what you're doing wrong, but this is working for me on Firebug's console:
var data = {"A5A50000":[{"bsid":"A5A50000","chanCount":17,"time":"2009-05-27 16:36:45","avgInterference":1.711765,"maxInterference":4.97,"avgHandsets":205.1176,"maxHandsets":315,"avgCalls":6.4118,"maxCalls":13,"avgCBA":3868.98059,"maxCBA":7463,"sumSuccessCBA":197318,"sumTimeoutHandoff":133,"sumAttemptHandoff":1028,"sumDeniedHandoff":216,"sumConfirmHandoff":679,"sumHandoffNetwork":61873,"sumJoinNetwork":96888,"sumLeaveNetwork":93754,"sumRcvdKeepalive":98773,"sumTimeoutKeepalive":19748,"sumAttemptUplink":93689,"sumBlockedUplink":62453}]};
var bsID = 'A5A50000';
alert(data[bsID][0].time);
In Javascript, you can use either object or array-style notation to look up an attribute. The following are equivalent:
data.A5A50000
data['A5A50000']
With the second syntax, you can use a variable in place of an object string:
data[bsID][0]
I experienced the same problem with a nested JSON API-response:
[
{
"bj_code": "2019",
"BJ_PERIODE": [
{
"nummer": 1
},
{
"nummer": 2
}
]
}
]
I could evaluate:
pm.expect(pm.response.json()[0].BJ_PERIODE[1].nummer).to.eql(2);
But working with BJ_PERIODE and nummer through a variable didn't work.
Writing it with the bracket method did work, even in this nested JSON, like this:
const periode = "BJ_PERIODE";
const nr = "nummer";
pm.expect(pm.response.json()[0][periode][1][nr]).to.eql(2);

Categories

Resources