I am using one 3rd party plugin which uses stringify and gives me something like:
["ProjectB","ProjectA","Paris"]
It was an array but it used stringify and serialized into this format.How do I get back my array from this? Now I could very well use split and then remove 1st and last character from every string and get it but I don't want to do that manually. Is that any built in utility that can do that for me?
Assuming you have like var str = '["ProjectB","ProjectA","Paris"]';
Try using,
var array = JSON.parse(str); //will return you an array
As #AlexMA pointed out: JSON.parse is not supported in old browsers so you are better off using jQuery version like below,
var array = $.parseJSON(str);
You can use
JSON.parse(your_arr_str);
or jquery
$.parseJSON(your_arr_str);
Related
I need convert following in the EXACT format shown below with javascript, could you please suggest how to achieve this
from: {"healthy":true,"unhealthy_reasons":[]}
to: [{"healthy":true,"unhealthy_reasons":[]}]
If that's all you need to do, you can just wrap array brackets around the variable that contains the object:
let initialObject = {"healthy":true,"unhealthy_reasons":[]};
let arrayedObject = [initialObject];
But I'm wondering if there's more to this. If this is actually part of a more complicated task, just add that to your question and you'll get a more complete answer.
Use JSON.parse() and JSON.stringify()
let data = '{"healthy":true,"unhealthy_reasons":[]}';
let parsed = JSON.parse(data);
//TO get an array
console.log([parsed])
//TO get a string
console.log(JSON.stringify([parsed]))
I have a JSON file that was processor generated with lines like this
jsonData: "{data: [350.23,250.32,150.34,340.50,236.70,370.45,380.55]}"
I can target the 'jsonData' object but that returns everything within the double quotes as a string.
I tried ...dataset[0].jsonData[8] which returns the '3' from the first value. I guess I could throw the mixed strings into a JS function and use regex to remove the extra stuff, but thats probably the hackyest way to do this.
Whats the easiest way to target the values only?
If you want to interact with it like the list I would consider something like
var list = jsonData.split("[")[1].split("]")[0].split(",")
Console.log(list);
The console reads:
[
'350.23', '250.32',
'150.34', '340.50',
'236.70', '370.45',
'380.55'
]
From here you can use list[3] to get 340.50
If you don't want to spend the time fixing your JSON just do this:
let values = "{data: [350.23,250.32,150.34,340.50,236.70,370.45,380.55]}".split(',').map(_ => _.replace(/[^0-9.]/g,''))
console.log(values)
The combination of my methods of declaring an array, adding elements to the array and applying the method toString() does not work. Essentially I enter a certain number (between one and five) values to textvariables : fontVorto1, fontVorto2, fontVorto3 ……… in the html-part of the document.
When I decide on leaving the remaining textelements empty, I click on a button, to assign them to an array, by way of the following function:
function difinNombroFv () {
var fontVortoj = new array();
fontVortoj[0] = document.getElementsByName("fontVorto1")[0].value;
fontVortoj[1] = document.getElementsByName("fontVorto2")[0].value;
fontVortoj[2] = document.getElementsByName("fontVorto3")[0].value;
……………….
and put them together in a string:
x = fontVortoj.toString();
document.getElementsByName("fontVorto")[0].value = x;
(the extra variable x is not needed) to enable me sending them to the next document, where I want to unserialize them with
$fontVortoj = unserialize($_POST["fontVorto"]);
I tested the method toString() by insering an alert(x), but the result was that I got for x the value of "fontVorto1" only.
I met solutions with JSON, jQuery etc., but I never used those "languages", only HTML, JavaScript, PHP.
Will my Christmas day be spoiled because of this simple problem ;>)?
couple of things to note:
1. var fontVortoj = new array(); . here new array() is not correct. it should be:
var fontVortoj = new Array();
now if you call fontVortoj.toString(), then it will convert the array and return a string with array elements separated by comma.
you can rebuild the array from the string in php by using "explode" function.
you can rebuild the array from the string in javascript by using "split" function.
Apparently I misunderstood the question to begin with.
To serialize an astray, you can use .join()
By default, it will give you the values, joined by commas.
To deserialize, use .split()
If there's a chance that there might be commas in your values, choose a more elaborate string for joining:
var ar = ["a", "b"];
var serialized = ar.join("|"); // "a|b"
var deserialized = serialized.split("|"); //["a", "b"]
The string that you use for joining and splitting can be as long as you like.
If you want to be completely covered against any values, then you need to look at JSON.stringify() & JSON.parse(). But that had browser compatibility issues.
I have a JSON object which looks like this:
[{"tabname":"orders","datagroups":[{"dataname":"ordersToday","datavalue":9},{"dataname":"orders30Days","datavalue":126}]}]
When I use console.log($.parseJSON(thedata))
I just get the word Object and no actual data.
How do I organise this data into a multidimensional javascript array? so that it looks something like this:
array("tabname"=>"orders", "datagroup"=>array(array("dataname"=>"ordersToday", "datavalue"=>9),array("dataname"=>"orders30Days","datavalue"=>126)))
It is an array:
var json = '[{"tabname":"orders","datagroups":[{"dataname":"ordersToday","datavalue":9},{"dataname":"orders30Days","datavalue":126}]}]';
var obj = $.parseJSON(json);
Array.isArray(obj) // => true
It's quite simple, really.
You can simply use jQuery's $.parseJSON (jsonString).
Thanks to everyone for contributing. I took a break then came back and figured it out. The way my brain works is all wrong.
To access the individual values, I needed to do something like this:
var orderStats = $.parseJSON(data);
console.log(orderStats[0].datagroups[0].dataname);
I have an array that contain some fields
like this
ctl00_ctl00_cphBody_bodycph_content_rdo_SID_25_SortOrder_17
ctl00_ctl00_cphBody_bodycph_content_rdo_SID_25_SortOrder_18
ctl00_ctl00_cphBody_bodycph_content_rdo_SID_25_SortOrder_19
I want to create a new array or manipulate this array to contain only
sid = {25,26,27}
from
_SID_25
_SID_26
_SID_27
where sid will be my array containing sid's extracted from above array
with pattern _SID_
I have to do this in jquery or javascript
use jquery map + regexp
var arr= ['tl00_ctl00_cphBody_bodycph_content_rdo_SID_25_SortOrder_17',
'ctl00_ctl00_cphBody_bodycph_content_rdo_SID_26_SortOrder_18',
'ctl00_ctl00_cphBody_bodycph_content_rdo_SID_27_SortOrder_19']
var out = $(arr).map(function(){
return this.match(/SID_(.*?)_/)[1];
});
out should be an array of the values..
(assuming all the values in the array do match the pattern)
I would use regex here
var sid = []
var matches = "ctl00_ctl00_cphBody_bodycph_content_rdo_SID_25_SortOrder_17".match(/_SID_(\d+)/);
if(matches) sid.push(parseInt(matches[1]));
This solution is totally reliant on the overall string form not changing too much, ie the number of "underscores" not changing which seems fragile, props given to commenter below but he had the index wrong. My original solution first split on "SID_" since that seemed more like a key that would always be present in the string going forward.
Given:
s = "ctl00_ctl00_cphBody_bodycph_content_rdo_SID_25344_SortOrder_17"
old solution:
array.push(parseInt(s.split("SID_")[1].split("_")[0]))
new solution
array.push(parseInt(s.split("_")[7])