How to convert Javascript array to JSON string - javascript

I have an array called values which has this data
var values=new Array();
values.push("english":"http://www.test.in/audio_ivrs/sr_listenglishMSTR001.wav");
values.push("kannada":"http://www.test.in/audio_ivrs/sr_listfrenchMSTR001.wav");
When I do JSON.stringify(values) I get values with square brackets, but I need a JSON string a shown below with urllist appended at the first.
{
"urlList":{
"english":"http://www.test.in/audio_ivrs/sr_listenglishMSTR001.wav",
"kannada":"http://www.test.in/audio_ivrs/sr_listfrenchMSTR001.wav"
}
}

Your code as you've defined it will give you errors. This is not valid JavaScript; you can't create an array element like this.
values.push("english":"http://www.test.in/audio_ivrs/sr_listenglishMSTR001.wav");
If you want the structure you've specified in your question then you'll need to use a nested object rather than an array to contain the key/value pairs.
var values = {
urlList: {}
};
values.urllist.english = "http://www.test.in/audio_ivrs/sr_listenglishMSTR001.wav";
values.urllist.kannada = "http://www.test.in/audio_ivrs/sr_listfrenchMSTR001.wav";
DEMO
HOWEVER...
Let's assume for a moment that what you meant to code was this (note the curly braces):
var values=new Array();
values.push({"english":"http://www.test.in/audio_ivrs/sr_listenglishMSTR001.wav"});
values.push({"kannada":"http://www.test.in/audio_ivrs/sr_listfrenchMSTR001.wav"});
This would tell me that you're pushing objects into an array which is perfectly valid JavaScript.
To get this information from the array into the structure you need you can use something like this loop:
var out = {
urlList: {}
};
for (var i = 0, l = values.length; i < l; i++) {
var el = values[i];
var key = Object.keys(el);
var value = el[key];
out.urlList[key] = value;
}
JSON.stringify(out);
DEMO

Related

Manipulate Json String Jquery

Supposed that I have this JSON STRING that is stored in a vairable:
{"name":"Joene Floresca"},{"name":"Argel "}
How can I make it
["Joene", "Argel"]
You mention you have a string. Use JSON.parse for that. Also, make sure it is an array. Afterwards, you can manually iterate through each object in the array and push the value
var str = '[{"name": "Joene Floresca"},{ "name": "Argel "}]';
var objA = JSON.parse(str);
var values = [];
for (var i = 0; i < objA.length; i++) {
for (var key in objA[i]) {
values.push(objA[i][key]);
}
}
console.log(values);
Assuming your JSON is an array, you can use map:
// Your JSON string variable
var jsonString = '[{"name":"Joene Floresca"},{"name":"Argel "}]';
// Parse the JSON to a JS Object
var jsObject = $.parseJSON(jsonString);
// Use map to iterate the array
var arr = $.map(jsObject, function(element) {
// Return the name element from each object
return element.name;
});
console.log(arr); // Prints ["Joene Floresca", "Argel "]
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can iterate over objects inside array and store the names in a second array.
var data = JSON.parse('[{"name":"Joene Floresca"},{"name":"Argel "}]');
var names = [];
data.forEach(function(model) {
names.push(model.name);
});
// names now contains ["Joene Floresca", "Argel"]
alert(names);

How to convert a string to an array based on values of another array in JavaScript

I have some data that I'm trying to clean up. For the field in question, I know what the possible values are, but the value is stored in a concatenated string and I need them in an array. Here is what I would like to do:
var valid_values = ['Foo', 'Bar', 'Baz'];
var raw_data = ['BarFoo','BazBar','FooBaz'];
desired_result = [['Bar','Foo'],['Baz','Bar'],['Foo','Baz']];
I'm not sure what this is called, so I hope this isn't a duplicate.
You can iterate over each data value, searching for allowed string with indexOf or contains and returning successful matches as array.
Here's my version of code and working example at jsFiddle:
var out = raw_data.map(function (raw) {
return valid_values.filter(function (value) {
return raw.contains(value);
});
});
//out === [['Bar','Foo'],['Baz','Bar'],['Foo','Baz']];
I assumed that output match order isn't important.
This is assuming some things about your data:
you need to split strings into 2-item pairs
input & terms are case-sensitive
you won't be dealing with null/non-conforming inputs (requires more edge-cases)
In that case, you'd want to do something like this:
// for each item in the desired result, see if it's a match
// at the beginning of the string,
// then split on the string version of the valid value
function transform(input){
for(i = 0; i < len; i++) {
if (input.indexOf(valid_values[i]) === 0) {
return [ valid_values[i], input.split(valid_values[i])[1] ];
}
}
return [];
}
// to run on your input
var j = 0, raw_len = raw_data.length, desired_result = [];
for(; j < raw_len; j++) {
desired_result.push(transform(raw_data[j]));
}
This code is pretty specific to the answer you asked though; It doesn't cover many edge cases.

how to generate arrays automatically in javascript?

I want to make a loop that makes arrays automatically and assign the values to it.
The problem is how to generate the array itself automatically.
for(var attGetter=1; attGetter <= num; attGetter++){
var catesArray1 = new Array();
for(var atttGetterArray=1; atttGetterArray <= series; attGetterArray++){
idOfInput = "cate"+chartGetter+"_series"+attGetterArray;
catesArray1.push($("#"+idOfInput).val());
}
}
I want the loop to generate the array itself automatically like
catesArray1
catesArray2
catesArray3
and so on..
You need an object or an array to hold the multiple arrays you wish to create. Maybe something you are looking for is like the following?
var arrayHolder = new Array();
for(var attGetter=1; attGetter <= num; attGetter++){
var catesArray = new Array();
for(var attGetterArray=1; atttGetterArray <= series; attGetterArray++){
idOfInput = "cate"+chartGetter+"_series"+attGetterArray;
catesArray.push($("#"+idOfInput).val());
}
arrayHolder.push(catesArray);
}
If you want the arrays to be in global namespace, You can try
window['catesArray' + attGetter] = [];
...
window['catesArray' + attGetter].push(...)
Else you can create a hash object and use it to hold the reference
var obj = {};
.....
obj['catesArray' + attGetter] = [];
.....
obj['catesArray' + attGetter].push(...)
In that case you will have to create one new array that holds all the cacatesArrays from first for loop
var catesArrayContainer = new Array(); //<<<---------------------
for(var attGetter=1; attGetter <= num; attGetter++){
var catesArray = new Array();
for(var atttGetterArray=1; atttGetterArray <= series; attGetterArray++){
idOfInput = "cate"+chartGetter+"_series"+attGetterArray;
catesArray.push($("#"+idOfInput).val());
}
catesArrayContainer.push(catesArray); //<<<--------------------
}
EDIT :
This happens because the scope of variable catesArray1 was limited. When the loop enters next iteration the catesArray1 gets reinitialized, thus losing all the previously stored values...
Now in the code I have posted, we are storing every instance of catesArray1 in another array, and your values persist out side of the for loop
You can do something like this for 4 arrays of 5 elements each
yourarray=[];
for (i = 0; i <4; i++) {
temparray=[];
for (j = 0; j < 5; j++) {
temparray.push($('#'+whateverID+'_'+i+'_'+j)) //your values here
}
yourarray.push(temparray);
}
Check it on this JSFiddle. open chrome console to see array
If you want to create array within loop from index
You can use eval to evaluate javascript from strings but i wont use that unless there is no other way. you can see both above and eval method in this Fiddle. Open Chrome console to see array values
Just a comparison of using eval and 2D array
Open console in chrome while you run this jsFiddle and you will see the difference in eval and 2darray in context of this question.
You should assign them to an object. In this case, make an object variable before the first for-loop to hold all arrays:
var allArrays = {};
for(var attGetter=1; attGetter <= num; attGetter++){
var currentArray = allArrays['catesArray' + attGetter] = new Array();
for(var atttGetterArray=1; atttGetterArray <= series; attGetterArray++){
idOfInput = "cate"+chartGetter+"_series"+attGetterArray;
currentArray.push($("#"+idOfInput).val());
}
}
Instead of attempting to create & allocate dynamically named variables, I would think of this more of an array of array's if you will. In other words, create an array that holds all of the arrays you want:
var collections = []; // Literal notation for creating an array in JS
From here, it's a matter of making each value you create within this array its own array:
var n = 10; // Total amount of arrays you want
for (var i = 0; i < n; i++) {
var values = [];
// Have another loop that fills in the values array as expected
collections.push(values); // Each element at collections[i] is its own array.
}
If you truly need named elements, you could potentially do something very similar with just an object {} instead, and refer to each element by a name you create.
var collections = {}; // Literal notation for an object in JS
var n = 10; // Total amount of arrays you want
for (var i = 0; i < n; i++) {
var values = []; // Literal notation for an array in JS
// Fill in the values array as desired
var name = 'arr' + i; // How you'll refer to it in the object
collections[name] = values;
}
I suggest the former though, since it does not sound like you need to have explicit names on your arrays, but just want multiple layers of arrays.

Can't reference array by index

I have an array defined as:
var subjectCache = [];
I then have some code to build it up, which is working ok.
However, if I try to reference the array by an index, e.g.:
var x = subjectCache[0];
or
var x = subjectCache[1];
I get undefined.
Also subjectCache.length is always 0 (zero).
if I try to reference it by its key, e.g.:
var x = subjectCache['12345'];
it works.
Is this normal? Shouldn't I be able to reference it by its index whatever?
I'm using Internet Explorer, if it makes a difference (and it probably does :( )
[Edit]
this is the code I'm using to build the array, although I really don't think it is to blame.
It's a callback from a webservice call. This is working fine and the array is being populated.
var subjectCache = [];
var subjectCacheCount = 0;
function refreshSubjectsCallback(data) {
// update subjects
// loop through retrieved subjects and add to cache
for( i=0; i < data.length; i++ )
{
var subject = data[i];
var subjectid = subject.SubjectId;
subjectCache[subjectid] = subject;
subjectCacheCount += 1;
}
}
[/Edit]
You're probably assigning keys manually instead of using subjectCache.push() to add new elements to the array:
var array = [];
array['foo'] = 'bar';
console.log(array.length); // 0
The length attribute isn't going to reflect those changes the way you'd expect:
> var a = [];
undefined
> a[100] = 2; // The previous `100` entries evaluate to `undefined`
2
> a.length;
101
Instead, use an object:
var object = {};
object['foo'] = 'bar';
for (var key in object) {
var value = object[key];
console.log(value);
}
From your symptoms, it sounds like you are trying to treat the array as an associative array.
In Javascript, arrays work like this:
var a = [];
a[1] = 10;
alert(a.length);
Objects work like this:
var o = {};
o.myProp = true;
o["myOtherProp"] = false;
Arrays only work with numeric keys not strings. Strings assign properties to the object, and aren't counted as part of length nor it's numeric indices.
When building the array, make sure you are assigning to a numeric position within the array.
No, it will not work, because you haven't created arrays but objects.
you will have to access it by its key.
var x = subjectCache['12345'];
If this works and subjectCache.length doesn't, I think you are making an object not an array. You are confused.
Somewhere along the road you lost the array, and the variable subjectCache points to a different kind of object.
If it was an array, it can't have the length zero and contain an item that is reachable using subjectCache['12345']. When you access an item in an array it doesn't make any difference if you use a numeric index or a string representing a number.

Simple way to import and export and store Arrays

For example I have something like this.
var Ar : Array;
Ar[0] = 'apple';
Ar[3] = 'pineapple';
Ar[12] = 'car';
Ar[33] = 'dog';
Ar[41] = 'cat';
Ar[21] = 'apple';
And I need to store it in simple text file. Like this
ArText : String ;
ArtText = "0-Apple,3-pineapple,12-car,33-dog,41-cat,21-apple"
You got the point.
What is best way to convert Array in to a readable string, and then back? Javascript code will be best, but you can use almost any similiar.
My initial impulse was to convert it directly to JSON, but then I realised that JSON.stringify() would return something like this:
["apple",null,null,"pineapple",null,null,null,null,null,null,null,null,"car",null,null,null,null,null,null,null,null,"apple",null,null,null,null,null,null,null,null,null,null,null,"dog",null,null,null,null,null,null,null,"cat"]
Because your array has a bunch of undefined slots that all become null because JSON doesn't support undefined values. Which would be OK if you just need to store it except then when you convert it back to an array you'd end up with nulls everywhere instead of undefined so you'd have to allow for that (not a big deal) but in any case it sounds like you want it to be human-readable too.
So instead I suggest you convert it to an object and then convert the object to JSON using JSON.stringify(). To convert it back you use JSON.parse() to turn your string into an object, then loop through the object properties to create a sparse array.
What I'm proposing would result in a JSON string like this:
{"0":"apple","3":"pineapple","12":"car","21":"apple","33":"dog","41":"cat"}
The code:
function sparseArrayStringify(arr) {
var obj = {},
i;
for (i=0; i < arr.length; i++)
if (typeof arr[i] != "undefined")
obj[i] = arr[i];
return JSON.stringify(obj);
}
function parseToSparseArray(str) {
var arr = [],
obj = JSON.parse(str),
k;
for (k in obj)
arr[k] = obj[k];
return arr;
}
var stringifiedArray = sparseArrayStringify(Ar); // where Ar is your array
// and change it back
var anArray = parseToSparseArray(stringifiedArray);
Working demo: http://jsfiddle.net/XXqVD/
Note: in my parseToSparseArray() function I didn't bother testing that the properties of the object in the string being parsed actually are non-negative integers, but you can add that if desired.
Newer browsers support the JSON object with associated methods, or for older browsers you can include the json2.js library.
By the way, the code in your question is invalid JavaScript: you can't declare variables with a type in JS. See the examples in my code for how to declare arrays, objects, etc.
EDIT: OK, I don't know why on earth you'd want the non-JSON version when JSON is a well known standard format, but here are some untested functions that read and write exactly the format from the question:
"0-Apple,3-pineapple,12-car,33-dog,41-cat,21-apple"
Note that your proposed format won't work if any of the array elements contain commas or hyphens. Which is why JSON is the way you should go. Anyway:
function serialiseArray(arr) {
var workingArray = [],
i;
for (i=0; i < arr.length; i++)
if (typeof arr[i] != "undefined")
workingArray.push(i + "-" + arr[i]);
return workingArray.join(",");
}
function deserialiseArray(str) {
var arr = [],
items = str.split(","),
item,
i;
for (i=0; i < items.length; i++) {
item = items[i].split("-");
arr[item[0]] = item[1];
}
return arr;
}
If it's just strings in the array, you could use the join() method on the Array object to create a comma separated string, and then use the split() method on the String object to convert the string back to an array.
var Ar = new Array;
Ar[0] = 'apple';
Ar[3] = 'pineapple';
Ar[12] = 'car';
Ar[33] = 'dog';
Ar[41] = 'cat';
Ar[21] = 'apple';
var stringRepresentation = Ar.join(",");
var backToArray = stringRepresentation.split(";");
You can see this working here; http://jsfiddle.net/ykQRX/. Note I've also fixed your invalid JavaScript (var Ar = new Array;).

Categories

Resources