How to parse the following json string into an object? - javascript

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.

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];

NaN When trying to print json values

I was trying to parse a json which I got as a response of querying connections in linked in.
when I do JSON.stringify in an array as a whole I can see values in console.log
but when I try to take individual values inside array I get NaN.
Why can I not get Individual values when I can see the array as a whole.
here is the code
var response = jQuery.parseJSON(data);
var person = response.person[0];
in the above code I am getting data as a response of an ajax call
person is an array inside, I can stringify the array as a whole.
if I do
console.log(JSON.stringify(person));
I will get
{"id":"someId","first-name":"someName","last-name":"someName, DMC-E, DMC-D","picture-url":"https://soempicture"}
but When I try to take it individually
console.log(person.first-name);
I get NaN , and trying to strigify it results in Null
am I missing something, should I do string split to get the values?
Thank you
You can't access the first-name property using period notation, as the name contains a dash.
The code will be interpreted as person.first - name, i.e. the person.first property minus the name variable.
Use the bracket notation for any property where the name can't be an identifier:
console.log(person['first-name']);
To access a key that contains characters that cannot appear in an identifier (-), use brackets, i.e.:
person["first-name"]

javascript array into object with same key names

I have an unusual problem to solve here. I have an array of Guids
[
"c01f8237-72c8-4fa6-9c53-1915750385aa",
"2c8a471b-c408-436c-81b1-3f3867d8ffb4",
"27a44d46-12bd-4784-ceed-57ada31b0e33"
]
This array has to be transformed into:
{
id: "c01f8237-72c8-4fa6-9c53-1915750385aa",
id: "2c8a471b-c408-436c-81b1-3f3867d8ffb4",
id: "27a44d46-12bd-4784-ceed-57ada31b0e33"
}
I know that shouldn't be done, but unfortunately cannot control the back end part. Any idea?
Thanks
The whole point of a dictionary key is that it uniquely maps to some value. Your desired output attempts to duplicate a key and therefore is neither possible nor does it make sense.
If you're passing this to a backend (as you suggest), then of course you can manually build a string to pass over the wire that duplicates keys in the payload, but you won't be able to actually do it in JavaScript first. You'll have to manually build the string.
Also note that you can call this format whatever you want, but you can't call it JSON and you can't use JSON libraries to build it (because it's not JSON). If your API expects a custom format, then you need to write code to build that custom format.
If all you want is a string just do something like
var str = '{' + idArray.map(function(id) {
return "id: "+id
}).join(',\n')+'}';
I have no idea what mime type you would put on that though since its not valid JSON.

JS: convert string into object

I have code
data = "{isShowLoginPopup:true,newFavOfferId:1486882}";
I want to convert it into JS object (not in JSON) and use it in this way:
data.newFavOfferId = ...
How can I do this?
If your source is trusted, the simplest solution is to use eval :
data = eval('('+data+')');
If you don't trust the source, then you'd better specify what you can have and parse the string manually (not terribly hard if you have only one level of properties for example).
Another solution (depending on your real data) would be to change your data into JSON by inserting the missing quotes :
data = JSON.parse(datareplace(/({|,)\s*([^:,}{]+)\s*(:)/g,'$1"$2"$3'));
just remove the quotes
data = {
isShowLoginPopup:true,
newFavOfferId:1486882
};
Fiddle: http://jsfiddle.net/QpZ4j/
just remove quotes "" from the
data = "{isShowLoginPopup:true,newFavOfferId:1486882}";
DEMO
Whilst on the surface this looks like JSON data, it's malformed and therefore it does not work directly with JSON.parse(). This is because JSON objects require keys to be wrapped in quotes...
therefore:
"{isShowLoginPopup:true,newFavOfferId:1486882}"
as valid JSON should be:
"{\"isShowLoginPopup\":true,\"newFavOfferId\":1486882}"
So what you have there in fact IS a JavaScript object, not JSON, however the problem you have is that this is a JavaScript object as a string literal. If this is hard coded, then you need to just remove the " from the beginning and end of the string.
var data = {isShowLoginPopup:true,newFavOfferId:1486882};
If this object is serialized and requires transmission from/to a server etc, then realistically, it needs to be transmitted as a JSON formatted string, which can then be de-serialized back into a JavaScript object.
var data = JSON.parse("{\"isShowLoginPopup\":true,\"newFavOfferId\":1486882}");

Get first item from comma delimited object

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];

Categories

Resources