JSON parsing issue in javascript - javascript

I have below result returned from python script
{"a_paget_wilkes": "\/speaker\/a_paget_wilkes.json",
"aaron_clark": "\/speaker\/aaron_clark.json",
"aaron_dunlop": "\/speaker\/aaron_dunlop.json",
"aaron_ernst": "\/speaker\/aaron_ernst.json",
"aaron_hurst": "\/speaker\/aaron_hurst.json",
"abigail_miller": "\/speaker\/abigail_miller.json",
"abner_kauffman": "\/speaker\/abner_kauffman.json"}
So it is pretty well formatted JSON I believe. Javascript variable which has above data is called jsondata. Now in the chrome developer tool console when I try to access key valye pair by typing jsondata. I expect all keys to be listed as suggestion, but it shows me string properties like length, anchor, big, blink etc... instead
I tried even JSON.stringify first and then JSON.parse but still the same!!!
Any idea what is wrong in here?

jsondata is apparently a string containing your JSON, rather than a JavaScript object that would result from parsing your JSON.
To parse it, use JSON.parse.
I tried even JSON.stringify first and then JSON.parse but still the same!!!
JSON.stringify will take you in the wrong direction — it will wrap your entire string in a JSON string — and JSON.parse will only undo the JSON.stringify (recovering your original string), not parse your original string.
You need to call JSON.parse without calling JSON.stringify first.

Related

How to parse the following json string into an object?

var jsonString = '{"DeviceId":3,"results":{"1":"[{\"x\":513,\"y\":565,\"width\":175,\"hight\":208}]"}}';
var message = JSON.parse(jsonString);
I got an error saying Unexpected token u in JSON at position 0
at JSON.parse.
Could you please guide me what's wrong?
THanks in advance!
At the last few characters looks wrong. The :212 has no sense as the value (that long array) for key "1" was already set, so that later :212 looks weird
Also enclosing it in single quotes it makes that all be like a huge string, and not as an array structure.
See Results key as value contains a sub array which contain "1" key which as value contains a string enclosing another json array (but escaped as plain string, so no structurally accesible for the main object . But that string if post -processed the :212 is paired to what? , no key, no comma neighter , to the precedent whole array which already was the value, not the key?. Anyway weird.
In your JSON string, there is wrong something with ":212", as it's not valid JSON, because it doesn't have any property that it's mapping the value for. For example, you are mapping values for width and height with properties keys. But for "212", there is no property.
Here is the above JSON formatted:
var jsonString = '{"DeviceId":"3","results":{"1":"[{\\"x\\":513,\\"y\\":565,\\"width\\":175,\\"hight\\":208}]"}}'
var message = JSON.parse(jsonString);
If you want to format the results, you can do to it, there is no error on it:
JSON.parse(message.results['1'])
Here is the JS Bin link for above code: https://jsbin.com/fiyeyet/edit?js,console
Just an advice
Professional code is all about proper spacing, proper identation , proper commenting, don't try to write down all within one single line, structure it VISUALLY nice to see nice to read nice to comprehend, and you will be approved in most jobs.
Hint: declare a normal array/object , convert it to json string using the proper function, then use the string variable returned by the function to test your code or whatever doing. That way, you can write down in the source really nice the structure.

JSON.parse not able to parse valid JSON object

JSON.parse throws error when I try to parse a valid JSON object. My issue is i'm receiving data from webservice and sometimes it works with parse and sometimes it doesn't not sure what is the reason why. I would expect JSON.parse to return same object if its a valid JSON object? or parse it if its a string.
var obj1= { Result: Inprogress };
var json = JSON.parse(obj1);
please help me with this understanding
What you have there is a JavaScript object. It doesn't need to be parsed because it's plain JavaScript syntax and JavaScript itself parses it. JSON is a serialization format.
The JSON.parse() method takes a string argument, like one retrieved from an ajax call or from local storage or some other source of data that only deals in string values.
Your JSON is malformed. A right JSON is
{ "Result": "Inprogress" }
You have forgotten the "" character in beginning and in end of each part of your JSON.

What is the right way to store JavaScript source code in a json object?

I want to edit JavaScript in a textarea and store it back into a JavaScript object. For example I have this object:
var item1 = {
'id' : 1,
'title':'title',
'sourcecode' : "alert('hallo')"
};
If I would change the content to alert("hallo") or a even more complex example does this break my object?
I would think there is some escape function like this https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/escape. But it is marked as deprecated.
So if this is deprecated what would be the right way for storing complex JavaScript code into a JavaScript object?
Should I use stringify ?
https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
The JSON.stringify() method converts a JavaScript value to a JSON
string, optionally replacing values if a replacer function is
specified, or optionally including only the specified properties if a
replacer array is specified.
This does not read like there is an automated escape build in.
If you need to send the data to a server, I'd say you should encodeURI your sourceCode, and then JSON.stringify the entire object. When retreiving data from the server, you should decodeURI the sourceCode

JSON.parse only parses parent object of string javascript

I'm trying to parse a string in javascript from rails into a javascript object,
{"monday":"{\"open\"=\u003e\"10:30\", \"close\"=\u003e\"24:00\"}"}
However after calling JSON.parse on it I'm returned with
Object {monday: "{"open"=>"10:30", "close"=>"24:00"}"}
How Can I make it parse not just the initial object, but it's child objects as well.
There are no child objects. The value of the "monday" key is a string, not an object. That is, if you expect subobjects, check the code generating the JSON, since it is wrong. The correct JSON for your use case would be:
{"monday":{"open":"10:30","close":"24:00"}}
While you could, obviously, get around this and parse this as it is, it would be like calling in a wrecking ball operator to punch you a new hole in your living room wall when you can't find your front door key.

parse json object from server side

IN my web service,I return one json object in the method:
{name:'xx'}
I use the ajax to send the request,then parse them using the 'eval'
onComplete:function(req){
var data=eval(req.responseText);
//do something according data
}
However,I can not get the 'data'.
When I retrun the following string:
[{name:'xx'}]
It worked,and I get the 'data' as an array.
Through google,I know that it is caused by the '{' in the return string.
So I wonder if there is no way to retrun a json object ?
Use JSON.parse or jquery's $.parseJSON - if you use jquery - instead of eval.
Also, if you do use jquery, you can take advantage of the built-in ajax method that automaticly retrieves and parses the response as a json object : $.getJson.
If you still don't want to modify your "logic", you can try to eval your response with added brackets : var data = eval('(' + req.responseText + ')');
Have a read of this blog post on JSON hijacking. The author explains the issue your running into
You might have seen code like the following when related to JSON:
eval('('+JSON_DATA+')');
Notice the beginning and ending parenthesis, this is to force
JavaScript to execute the data as an object not a block statement
mentioned above. If JavaScript did attempt to execute JSON data
without the parenthesis and the JSON data did in fact begin with “{”
then a syntax error would occur because the block statement would be
invalid.
...more info on why...
Rather than adding () around your JSON response, you should be using JSON.parse or $.parseJSON like gion_13 has said. Eval isn't the way to go.
Also, like quentin said in the comments, you need to change the JSON you're returning as it's invalid. You need to quote your key as well as your value.
It worked,and I get the 'data' as an array.
That's what it's supposed to do. [] is the syntax for declaring an array. If you want the inner object, then just return {name: 'XX'}.

Categories

Resources