JSON.parse not evaluating JSON strings properly - javascript

I am using JSON.parse to parse this JSON string
[{"created_at":"2012-01-24T22:36:21Z","name":"joe","age":42,"updated_at":"2012-01-24T22:36:21Z"}]
However I am simply getting this result as the output:
[object Object]
Which shouldn't be the result. I am using this within the Cappuccino framework. Does anyone know what I am doing wrong here?

[object Object] is what objects display when you call toString on them. It looks like you're taking your result and trying to call obj.toString()
Also, your JSON is an array with one element in it, so to verify that your result is correct, you can access the name property on the [0] index:
obj[0].name // should be "joe".
var text = '[{"created_at":"2012-01-24T22:36:21Z","name":"joe","age":42,"updated_at":"2012-01-24T22:36:21Z"}]';
var obj = JSON.parse(text);
alert(obj[0].name); //alerts joe
DEMO
Or get rid of the array, since it's not really doing much
var text = '{"created_at":"2012-01-24T22:36:21Z","name":"joe","age":42,"updated_at":"2012-01-24T22:36:21Z"}';
var obj = JSON.parse(text);
alert(obj.name); //still joe
DEMO

This is an array because it's in square brackets - [] - remove these and it should work...
Even though this is 'syntactically' correct the parser sees this as an array (which is a type of object) but won't do the work on it the way you'd expect.
Also for future reference:
Try to lint it, and see if your syntax is messed up: http://jsonlint.com/

This is an old subject, but nonetheless, I spent hours trying to figure out what was going on. So, hopefully this will help someone else in the future.
My issue was setting up a simple ajax call, and doing something with the resultset from said ajax call. However, no matter what I did, I couldn't get the json resultset to an object.
I ended up stepping through everything in the debugger window and noticed old code that was no longer active was showing up on the sidebar (dom detail). So, my data had been cached. I cleared the cache, and boom! Everything worked.

Related

getComputedStyle Font Family returns multiple families [duplicate]

Hi I have an object rowObject passed into a javascript function. When I inspect it by putting it into an alert I see something like:
435,345,345345,56456
What I want to achieve is to get the first integer ie. 435 from the list.
I know how to do this in server side code but client side code.
Can someone please help me with this?
Assuming that your rowObject is a string, you can use .split() to split the comma delimited list. At this point you can access the array of items by index and get the first element.
http://www.w3schools.com/jsref/jsref_split.asp
An Example
var rowObject = "435,345,345345,56456";
var splitRowObject = rowObject.split(',');
if(splitRowObject.length > 0)
alert(splitRowObject[0]);
alert() is calling objects toString() method, so you don't know the structure of the object. It is a good idea to use console.log instead for logging objects as in modern browsers it will allow you to explore structure of the object in the console window.
One of the solutions you can do without knowing the structure is:
var firstInteger = +rowObject.toString().split(',')[0] // 435
That works if rowObject is string, array or everything else :).
EDIT: Putting + before the string will try to convert it to a number.
Have you tried rowObject[0]?
The fact that the alert shows 435,345,345345,56456 doesn't mean that the object is string, it could be Object and Array as well as their toString method implemented to display it in such way. For example the native array is also looks like that when alerting or converting to string, so you need to call toString method at first then split it by comma:
var firstInt = rowObject.toString().split(',')[0];

Simple JSON stays undefined

I have an AJAX call that get's a simple JSON back on success, writing the returned JSON into the variable named data.
The returned JSON has been generated within PHP through:
echo json_encode(array('message'=>0);.
Back in my javascript console I'm logging the output of data with console.log(data);. The output is {"message":0}, which seems correct.
However, if I try to log console.log(data.message); I am getting message: undefined.
What am I doing wrong in accessing this pretty basic JSON object?
I've been reading some articles about how to move through JSON object, e.g. https://www.tutorialspoint.com/json/json_overview.htm but I can't find my mistake.
Hopefully you can point me into the right direction :)
Thank you :)
You have to do JSON.parse(result) first to make it an object, because at the moment you're trying to access message property of a string.
You know there are 2 JSON functions in javascript, right...?
// returns string representation of the object
JSON.stringify(object);
// returns a new object built from the string
JSON.parse(object_stringified);

jquery console.log and alert different value

I realy cant understand javascript. Maybe someone can explain me the difference:
validationErrors[value.element.name] = value.method;
console.log(validationErrors);
alert(validationErrors);
console.log(validationErrors) returns well formed array with values, and alert(validationErrors) returns empty array. Why?
The console is more of a debugging environment and can understand the JS objects that are passed in the log function.
Alert on the other hand is a dialog box and will coerce its arguments into string values. Which is why the output is not as well formatted as the console.
Here is a little snippet of what is actually happening in the alert box.
var validationErrors = [ 2, 3, 4 ];
console.log(toString(validationErrors));
Output >> "[object Window]"
It's also best practice to use the console for logging purposes and not the alert box.
you can try this
alert(JSON.stringify(validationErrors));
Alert have some limit according to browser it varies but most You'd probably be best staying under 1000 characters though, as many browsers seem to begin to truncate after 999.
And if you are giving object in alert it will never reflect the values so prefer console for object and other data type can be used in alert but its not a good practice.
console give proper view of data like object in array can be studied easily in console.
Alert is used to print messages, which means it is used to display string values. When you pass anything other than string to alert, it calls .toString function of it and prints the output.
Now why did you get a blank string?
An array is supposed to have indexed values only. So you can do array[index] = "bla bla". But when you do array["something"] = "something else", it adds a property to that array (since arrays are also objects in Javascript).
According to MDN
The toString() method returns a string representing the specified array and its elements.
In simple, it will loop over length of array and join all elements with ,(comma)
But you do not have elements in it. You have set properties. So length is 0 and hence it returns ""
Following is a simulation
var a = [];
a["test"] = "foo";
console.log(a);
console.log(a.toString());
alert({})
Reference
Alert
Array.prototype.toString
All objects in Javascript are passed by reference. So when you passed something to console.log() and it would be changed in code further, in console you will see changed value. On other hand, alert() displays message box and stops code execution, so in message box you see values exactly as they are at alert()'s call time.
For debugging purposes, you may want to use browser's debugger - I recommend Chrome Dev tools. There is free course from codeschool.com to help you discover such great tool: https://www.codeschool.com/courses/discover-devtools

Why does this simple JSON object throw an error with JSON.parse?

Anyone can probably figure this out. Why does the following JSON object cause a JSON.parse error? It appears to be a valid JSON object. I'm sure I'm doing something completely idiotic in this, the 14th hour of this long workday.
var t = {
"message": "ok, Heru we go!"
};
JSON.parse(t);
--> syntaxError: Unexpected token o
Many thank yous!
UPDATE
This is the kind of question you ask when you have 2 new puppies and are trying to code on 3 hours of sleep. Please let this serve as a warning for those of you who have come here looking for the same answer- Go to sleep. Give it up. You're worthless today. Try again tomorrow.
JSON.parse expects a string. The value of t is a javascript object, so it doesn't need to be parsed.
If you had:
var t = "{\"message\":\"ok, Heru we go!\"}";
then JSON.parse would be what you were after.
Don't you want JSON.stringify(t);?
JSON.parse(s); is used to get the object out of a string.
JSON.stringify(t); is used to convert your JSON object to its string equivalent.
t is already a JavaScript object. JSON.parse only works on strings. You could do JSON.parse(JSON.stringify(t)), but that would be kind of pointless.
The JSON here should be a string. You are passing an object as parameter.
Try this
JSON.parse('{ "message": "ok, Heru we go!" }');

(object Object) returning from JSON request in Node

I have another simple question about Node. I'm trying to make a simple http request to the Open Courseware search API (http://www.ocwsearch.com/api), but I'm running into some problems actually parsing the JSON... which normally hasn't been a problem.
The request returns a string that has escaped characters and slashes, and so I've run a replace and an unescape on the response string, but this ends up returning something like '[object Object]'. Right now, all I really want to do is be able to SEE what's finally being returned, so I can tell whether or not I can finally parse it as valid JSON. Unfortunately, this is not working either. I've read a couple of similar threads on stack overflow, but I'm still unable to get it to work.
What I've tried:
iterating over the object being passed, because I thought it'd be something with key value pairs, and running over it, logging it each time. However, this prints it out as a string:
[
o
b
...
all the way to the end (])
Given x as the returned formatted object in question,
using "" + x, toString(), to try to convert it to a string
using console.log("%j", x) as per How do you log content of a JSON object in Node.js?
None of these seem to work though, they're all returning me [object Object].
I've even tried it in jsfiddle: http://jsfiddle.net/S47QL/2/
I'm replacing console.log with alert, and it seems to be re
My code:
var request = require('request');$
request('http://www.ocwsearch.com/api/v1/search.json?q=' + skill + '&contact=http%3a%2f%2fwww.ocwsearch.com%2fabout/',$
function(error, response, body){$
if(!error && response.statusCode == 200){~$
console.log(response.toString().replace(/\\\//g, "/"));$
var x = response.toString().replace(/\\\//g, "/");$
console.log(x)$
console.log(x.keys());$
}$
});$
Right now, all I really want to do is be able to SEE what's finally being returned, so I can tell whether or not I can finally parse it as valid JSON.
So then make the request in a browser window (using Chrome you can see the actual results being returned in the inspector tabs - press F12).
Example: http://www.ocwsearch.com/api/v1/search.json?q=ios&contact=http%3a%2f%2fwww.ocwsearch.com%2fabout/
And according to http://jsonlint.com/ this is valid JSON being returned. Are you sure you're not trying to be too smart for your own good?
You can't write the response to string, because it's an object. You need the data returned, but I think the body field does what you want. Have you tried just printing body?

Categories

Resources