convert array stored in a string to an array - javascript

I have an array value which is coming from database as an string. I need to convert it into an array. When I check my value in console I can see value as
"[["COL1","COL2","COL3"],["COL4","space,"COL5"]]"
In order to perform my operations I need it to be in below structure
[["COL1","COL2","COL3"],["COL4","space,"COL5"]]
I have already tried JSON.parse() and parseJSON
Expected Result :
[["COL1","COL2","COL3"],["COL4","space,"COL5"]]
Actual Result :
"[["COL1","COL2","COL3"],["COL4","space,"COL5"]]"

You need to remove the outer quotes from your string, then pass the value to JSON.parse() to get the array.
Also, you have to quote each item correctly, "space should be "space".
You can sanitize the string with String.prototype.replace() (assuming the quoting of space has been fixed in the DB):
const data = '"[["COL1","COL2","COL3"],["COL4","space","COL5"]]"';
const dataSanitized = data.replace(/^"|"$/g,"");
console.log(JSON.parse(dataSanitized));

I would suggest you do parse
JSON.parse('[["COL1","COL2","COL3"],["COL4","space","COL5"]]')
i would not suggest eval as i just read an article about "how eval is evil"
https://javascriptweblog.wordpress.com/2010/04/19/how-evil-is-eval/

Related

How do I access the value of an array property?

How do I access the value stored in the description property using javascript?
As seen in the image below (a screenshot from the browser console), the stored value is [STK_CB - ] Request Cancelled by user
In the browser console, I have tried console.log(responseMan.payload["0"].jsonPayload.description); which shows undefined. Where am I going wrong?
Looking forward to your help.
The value of jsonPayload is a string, not an object -- notice the double quotes around it. And the name of the property implies that it's JSON. You need to call JSON.parse() to convert it to an object.
var payload = JSON.parse(responseMan.payload[0].jsonPayload);
console.log(payload.description);
just remove " from index and do it like:
u also have to cast the json first
const jsonStr = responseMan.payload[0].jsonPayload;
const data = JSON.parse(jsonStr);
console.log(data.description);
The problem is in your json. Because you are trying to access responseMan.payload ["0"]. JsonPayload up there is a correct element in the json. But the description is a string value in responseMan.payload ["0"]. JsonPayload, therefore, must format the contents of responseMan.payload ["0"]. JsonPayload on a json object. Example var obj = JSON.parse (responseMan.payload ["0"]. JsonPayload); and so
description will be a json object
OR
You can fix that json in your backend and send that section as a json and not as a string

Prevent JSON.parse from rearanging an object

In my web application I receive a JSON string from the server which I keep in the greetings variable:
var greetings = '{"2":"hoi","3":"hi","1":"salam"}'
Please notice how the greetings start with the index 2 and the value hoi.
Now I want to parse the JSON and the result is the following:
JSON.parse(greetings) // {1: "salam", 2: "hoi", 3: "hi"}
The order has changed, it seems like JSON.parse orders the result by key.
Is there a way to keep the order of the original string intact?
{
"2":"hoi",
"3":"hi",
"1":"salam"
}
is not an array, its an object. Objects don't have any order.
If the order is important, you need to switch to an actual array.
You generally cannot rely on the order of indices in an object. Use an array of key/value pairs instead.
As you can see the keys are parsed to (numeric) indices, which is why they are ordered that way. You could hack around this by prefixing your keys and then stripping those later:
console.log(JSON.parse('{"i2":"hoi","i3":"hi","i1":"salam"}'))

Converting object to array/string

"system_details":
{
"ucs_version":"00.02",
"ucs_crash_id":"1500000000002A30040000003002B038",
"ucs_static_id":"0x1500000000002A30",
"ucs_variable_id":"0x040000003002B038"
}
I have a javascript object -json, whose value is as above.
1.How can i store each character from json into a array?
a[0]=", a[1]=v,a[2]=e and so on...........
2.How can i convert the json to a string or key-value pair?
if a want value of the 'version' from json, it should output me value 00.02.
The code shown is already an object, so objName.system_details.ucs_version will return "00.02".
To turn the obj into a string, use JSON.stringify( objName );
To store the characters of a string into an array, you can split it on nothing, so string.split('') will just split a string into all its characters.
Eg. "system_details".split('') becomes ["s","y","s","t","e","m","_","d","e","t","a","i","l","s"]
Note that the " around each key and value is not part of the string, so if your array needs to include these, you'll have to add them to the front and the back of the array after splitting the string.
Hope it helps.
convert your object to string use simple java script function => JSON.stringify
try this boss
JSON.stringify( Your_object);

How to get an inner object literal value with javascript

After calling console.log(JSON.stringify(req.params)), I get a string with the following structure:
{"q":"{\"email\":\"mymail#mail.com\"}","apiKey":"1234"}
With console.log(req.params.q), I have this result: {"email":"mymail#mail.com"}.
But I get "undefined" if I try to view the email value with console.log(req.params.q.email) or console.log(req.params.q["email"])
What is the best approach to get that value?
You must JSON.parse that inner part :
var test = {"q":"{\"email\":\"mymail#mail.com\"}","apiKey":"1234"};
alert(JSON.parse(test.q).email);
alerts mymail#mail.com
Why?
Because test holds an javascript object where q holds a string, So you must parse that string if you want to extract the JSON values from that string.
It looks like req.params.q is a string: "{\"email\":\"mymail#mail.com\"}".
You need to parse that json then fetch the value.
req = {params: {"q":"{\"email\":\"mymail#mail.com\"}","apiKey":"1234"}}
JSON.parse(req.params.q)
> Object {email: "mymail#mail.com"}
JSON.parse(req.params.q).email
> "mymail#mail.com"

Retrieve JSON Array element value

My web service returned a JSON Array (ie. [{"key":"value"}, {"key":"value2"}]). In the array there are two items as you can see, which are separated with comma. I want to know how can I access the second item, and get the value of "key" for the second item.
I've tried:
var a = msg.d[1].key
With no success of course.
This is the returned string:
"[{"Code":"000000","Name":"Black","Id":9},{"Code":"BF2C2C","Name":"Red","Id":11}]"
The string was extracted using FireBug after watching the msg.d.
Need your help in solving this.
msg[1].key
Assuming that the name of that array is msg. I'm not sure what you are using .d for.
If msg.d is a string representing an array, use JSON.parse.
JSON.parse(msg.d)[1].key
You can replace key with the key you are wanting, e.g. Code, Name, Id, etc.
This works as expected for me.
var msg = [{"key":"value"}, {"key":"value2"}];
var a = msg[1].key;
What is msg in the example above? Need more info to help.
If msg.d is a string then you have to eval (uggh) or parse it before applying the array subscript.

Categories