Can't get the value of json object - javascript

I have this json object, and i want to get the value of the error but it always returning me an undefined result.
Here is the json object
{"isValid":false,"errors":["Username is required.","Password is required."]}
my code is:
success: function (response) {
var JSONstring = JSON.stringify(response);
var JSONobject = JSON.parse(JSONstring);
alert(JSONstring);
alert(JSONobject);
console.log(JSONobject);
var _result = JSONobject.errors;
i have also tried:
var _result = JSONobject[0]['errors'];
var _result = JSONobject['errors'][0];
but still i can't access the value.

If you already have access to the JSON object you can work with it without manipulation. If your question was also looking to get it in that form, see this StackOverflow answer for how to format your request.
success: function (response) {
// Assuming response = {"isValid":false,"errors":["Username is required.","Password is required."]}
// Directly access the property errors
var errors = response.errors;
console.log(errors); // ["Username is required.","Password is required."]
JSFiddle

Related

How to assign (add) value to a undefined item in a json object

I have a external json file and I parse it in to local object,
Currently I know I can't push value into a object so I want to assign a value to them here is my code:
//I parse my JSON into object and name it data
var data = {
...
}
// I use this object as a database so I don't list it all out
var name = "title";
var content = "hello guys";
data[name] = content;
// I wish after this script the object will have one more item like
// {
// ...
// "title": "hello guys",
// ...
//}
But the vscode's console show the following error when I run the script
TypeError: Cannot set property 'title' of undefined
If you can assign value to undefined object how can you add item in to object.
But if there is any way that can let me assign value to undefined item, I'll be very happy
Here is the full code if you need
var jsonfile = require('jsonfile')
var file = './test.json'
var data = jsonfile.readFileSync(file); //I'm very sure data isn't undefined
//console.log(data);
var name="title";
var content="hello guys";
data.post[name] = content;
jsonfile.writeFileSync(file, tmd, {spaces: 4});
currently data = undefined and you are trying to access a key in undefined that is why you are getting an error, you need to assign an empty object to data if it is undefined. you can do something like this:
var data = data || {};
var name = "title";
var content = "hello guys";
data[name] = content;
Probably data has no key named 'post'.
Try this:
data.post = data.post || {};
data.post[name] = content;
EDIT:
I know this is old, but maybe it will help someone.
Here https://nodejs.org/api/fs.html#fs_fs_readfilesync_path_options states that readFileSync returns string not data structure.

Unable to access JSON Element in Javascript via Object.property

I am unable to access a simple JSON Element from a JSON Structure that looks like:
{
"ACTION": "AA",
"MESSAGE": "Customer: 30xxx Already Approved on 2017/01/01"
}
I get the data in JSON Format but when i do data.ACTION or data.MESSAGE i get Undefined as the output.
By doing case sensitive also, its not working( Image attached )
var url = base + query;
var getJSON = function (url) {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.withCredentials = true;
xhr.onload = function () {
var status = xhr.status;
if (status == 200) {
resolve(xhr.response);
} else {
reject(status);
}
};
xhr.send();
});
};
getJSON(url).then(function (data) {
console.log(data); //Getting JSON Data
var output = JSON.stringify(data);
var obj = JSON.parse(output.replace(/ 0+(?![\. }])/g, ' '));
console.log(output);
console.log(obj.message); //Here getting UNDEFINED
}, function (status) { //error detection....
alert('Something went wrong.');
});
Console:
{"ACTION":"AA","MESSAGE":"Customer No. 0000030332 Already Approved On 20170113"}
stringify returns the following
{\"ACTION\":\"AA\",\"MESSAGE\":\"Customer No. 0000030332 Already Approved On 20170113\"}"
EDITED. I first thought the error was due to parsing, given the print. -.-
Solution:
When you print the output, obj it's still a string, not an object. So it is OK at that point.
Your "undefined" property message should be replaced by MESSAGE.
Instead of console.log(obj.message); just use console.log(obj.MESSAGE);
Also. An example of parsing JSON:
var myJson = '{"ACTION":"AA","MESSAGE":"Customer No. 0000030332 Already Approved On 20170113"}';
console.log(myJson); // This prints the literal string
console.log(JSON.parse(myJson)); // this prints an "object"
obj.message property is not defined and when you try to get the property which is not defined on an object, you get undefined.
Javascript is case sensitive. You should try obj.MESSAGE instead to get the property value. Also, to check if a property exists on an object you can make use of object.hasOwnProperty([propName]) method to check if a property exists on a object or not.
EDIT 1: Try running the following code snippet. JSON data string is parsed before accessing the property.
var jsonString = "{\"ACTION\":\"AA\",\"MESSAGE\":\"Customer No. 0000030332 Already Approved On 20170113\"}";
var obj = JSON.parse(jsonString);
console.log(obj.MESSAGE);
data already is a JSON string, there's no need to JSON.stringify it (which returns a string with a JSON-encoded string literal). Parsing it into output only leads to a string again, which has no properties. You should use
console.log(data);
var obj = JSON.parse(data);
console.log(obj);
obj.MESSAGE = obj.MESSAGE.replace(/ 0+(?![\. }])/g, ' ');
(notice the proper casing of the property name)
You can try:
var jsonObject = data.data;
console.log(jsonObject.ACTION)

How to use ajax filter

I'm trying to filter out some values from an AJAX call. Here's what I have tried:
var year = 200908; // for example
var resultArray = data.filter(function (a) {
return a.proddate == year;
});
var firstTask = resultArray[0];
var lastTask = resultArray[resultArray.length - 1];
data is coming from success function in an ajax call. But I'm getting this error:
JavaScript runtime error: Object doesn't support property or method 'filter'
Here is a sample of the returned data:
"[{
"tasknum":6,
"dependtask":5,
"jobname":"prc",
"proddate":"200908",
"activity":"Pr‌​elim",
"groupname":"CNSPROD-EST",
"parametername":"n/a",
"parametervalue":"n/a"
}]"
Any ideas?
First, try doing a console.log on data and verify what exactly you're retrieving. filter only works on arrays so this would work:
var resultArray = [1,2,3].filter(function(a) {
return a > 2;
});
But this will not:
// "Object doesn't support property or method 'filter'"
var resultArray = {1: true, 2: true, 3: true}.filter(function() { ... });
I suspect that data is not the variable assigned to the response. Or perhaps you haven't parsed response to js array from JSON using JSON.parse()
Your code works fine here:
DEMO

JSON anonymous type property undefined?

in my mvc3 roject, I return the Json object:
return Json(new { ID = guid, FileName = file.FileName, FullPath = filename });
then, in the JS code, I try to acces to the fields, e.g:
onComplete: function (event, queueId, fileObj, response, data) {
alert(response.ID); //test
}
but i get the undefined message. If i just get the alert(response); I see the valid object:
{"ID":"22186ea1-a56a-45d1-9d13-d19f003dedf9","FileName":"file.txt","FullPath":"some_path"}
so how to access to that properties ?
You're probably seeing the JSON text that needs to be parsed into JavaScript data structures.
var parsed = JSON.parse(response);
alert( parsed.ID );
Without parsing it, you're trying to access the ID property of a String object.
var str = '{"ID":"22186ea1-a56a-45d1-9d13-d19f003dedf9","FileName":"file.txt","FullPath":"some_path"}';
alert( str.ID ); // undefined

Get json value from response

{"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}
If I alert the response data I see the above, how do I access the id value?
My controller returns like this:
return Json(
new {
id = indicationBase.ID
}
);
In my ajax success I have this:
success: function(data) {
var id = data.id.toString();
}
It says data.id is undefined.
If response is in json and not a string then
alert(response.id);
or
alert(response['id']);
otherwise
var response = JSON.parse('{"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}');
response.id ; //# => 2231f87c-a62c-4c2c-8f5d-b76d11942301
Normally you could access it by its property name:
var foo = {"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"};
alert(foo.id);
or perhaps you've got a JSON string that needs to be turned into an object:
var foo = jQuery.parseJSON(data);
alert(foo.id);
http://api.jquery.com/jQuery.parseJSON/
Use safely-turning-a-json-string-into-an-object
var jsonString = '{"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}';
var jsonObject = (new Function("return " + jsonString))();
alert(jsonObject.id);
var results = {"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}
console.log(results.id)
=>2231f87c-a62c-4c2c-8f5d-b76d11942301
results is now an object.
If the response is in json then it would be like:
alert(response.id);
Otherwise
var str='{"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}';

Categories

Resources