I have a JavaScript variable with comma separated string values - i.e. value1,value2,value3, ......,valueX,
I need to convert this variable's values into a JSON object. I will then use this object to match user enteredText value by using filterObj.hasOwnProperty(search)
Please help me to sort this out.
What you seem to want is to build, from your string, a JavaScript object that would act as a map so that you can efficiently test what values are inside.
You can do it like this :
var str = 'value1,value2,value3,valueX';
var map = {};
var tokens = str.split(',');
for (var i=tokens.length; i--;) map[tokens[i]]=true;
Then you can test if a value is present like this :
if (map[someWord]) {
// yes it's present
}
Why JSON? You can convert it into an array with split(",").
var csv = 'value1,value2,value3';
var array = csv.split(",");
console.log(array); // ["value1", "value2", "value3"]
Accessing it with array[i] should do the job.
for (var i = 0; i < array.length; i++) {
// do anything you want with array[i]
}
JSON is used for data interchanging. Unless you would like to communicate with other languages or pass some data along, there is no need for JSON when you are processing with JavaScript on a single page.
JavaScript has JSON.stringify() method to convert an object into JSON string and similarly JSON.parse() to convert it back. Read more about it
All about JSON : Why & How
Cheers!!
JSON format requires (single or multi-dimensional) list of key, value pairs. You cannot just convert a comma separated list in to JSON format. You need keys to assign.
Example,
[
{"key":"value1"},
{"key":"value2"},
{"key":"value3"},
...
{"key":"valueX"}
]
I think for your requirement, you can use Array.
Related
I am using angular5.I have a questionOrderList which is a string which contains multidimensional array in string format. What I need to do is to parse the array in string format back to multidimensional array type. Currently I have used the JSON.parse method my code looks like.
console.log("qorder service : "+questionOrderList)
console.log("qorder service parsed:" +JSON.parse(questionOrderList))
The output I am getting is
qorder service : [[3290],[3287],[3289,3293],[3295]]
qorder service parsed: 3290,3287,3289,3293,3295
But in case of array with one row it is correct
qorder service : [[3290,3287,3289,3293,3295]]
qorder service parsed: 3290,3287,3289,3293,3295
What you are going is correct, see this:
var questionOrderList = "[[3290],[3287],[3289,3293],[3295]]";
var parsedList = JSON.parse(questionOrderList);
console.log(parsedList)
The actual issue is how JS interprets string concatination with arrays. It implicitly calls .join(',') on the array as demonstrated here:
var questionOrderList = "[[3290],[3287],[3289,3293],[3295]]";
var parsedList = JSON.parse(questionOrderList);
console.log(parsedList);
console.log("" + parsedList);
console.log(parsedList.join(','))
I have json returned from Database.I want to pick only one object Value and show it in the textbox. Here is my json.
[{
"ErrorMessage":"",
"ID":294,
"ExpenseID":0,
"EffectiveDate":"/Date(1262284200000)/",
"FormattedEffectiveDate":"01-01-2010",
"Perunit":null,
"VATRate":17.5,
"ChangedByID":1,
"ChangedByName":"superuser, superuser",
"Expense":null,
"ErrorSummary":null,
"ErrorList":[]
}]
I have Tried
var Jsoninvoice = JSON.stringify(data)
alert(Jsoninvoice.VATRate) and also alert(data.VATRate)
Thank you In advance.
You have an array containing 1 object. stringify turns this object into a string - you need it parsed so you can use it.
(I'm not sure if the object is parsed already, so to cover all bases, we'll parse it)
var Jsoninvoice = JSON.parse(data);
alert(Jsoninvoice[0].VATRate);
You have to specify the arrays index before you can access the properties.
It is already json object and stringify is not needed as #tymJV said you need to parse it if it is returned as string, just you need to access array item, as it is an array:
alert(data[0].VATRate)
SEE FIDDLE
You could use $.parseJSON(YOURJSON), and then use the keys to pull the data. Since it's in an array, you'll have to use [0] to pull the first item in the array (ie: your data).
Example
$(document).ready(function(){
var j ='[{"ErrorMessage":"","ID":294,"ExpenseID":0,"EffectiveDate":"/Date(1262284200000)/","FormattedEffectiveDate":"01-01-2010","Perunit":null,"VATRate":17.5,"ChangedByID":1,"ChangedByName":"superuser, superuser","Expense":null,"ErrorSummary":null,"ErrorList":[]}]';
var json = $.parseJSON(j);
alert("VATRate: "+json[0].VATRate);
});
Fiddle for reference
I'm using a one-off language similar to javascript in syntax, so an answer in that more common language should suffice.
I have a list of name/val pairs that i built from a big GET string that looks something like
"n1=v1,n2=v2..."
I'm not sure that my initial approach is correct. I used a primitive in this language
tolist(GETstring,"=")
to split the name value pairs into the above list. Perhaps, this is the wrong approach from the gate.
This gives me
data = [["n1","v1"],["n2","v2"],...]
I'm trying to change this into a named array, such as
data["n1"]="v1";
data["n2"]="v2";
...
so that I can access items by name, not by list index (as it is highly volitale)
What is the better approach to getting the data in this format. I've tried a few including evals but nothing seems to work.
You'll have to split the string up then iterate through it.
var obj = {};
var originalString = "n1=v1,n2=v2";
var splitOriginalString = originalString.split(",");
for (var i = 0; i < splitOriginalString.length; i++) {
var tmpObj = splitOriginalString[i].split("=");
obj[tmpObj[0]] = tmpObj[1];
}
There is no option to do it. You've got two ways to do workaround.
Create two arrays, one for keys and one for values.
var indexes = ["test", "test2"];
var values = ["val", "val2"];
var value = values[indexes.indexOf("test2")]; // will get "val2"
Create nested array with key 0 for your string key and with 1 for its value.
I have a form and would like to append the contents of it to an existing array.
I am using JSON.stringify( $('#myForm').serializeObject() ) to convert my form elements into json objects.
The form has user info that i would like to append into myArr then append this list into an existing array.
myArr is populating fine, its just appending that into existingJsonArray i seem to be having problems with.
I saw this but since JSON.stringify creates the full json array would i need to knock out the [{ and }] ?
Is this the correct approach?
var existingJsonArray = [];
var myArr = [];
myArr.unshift( JSON.stringify( $('#myForm').serializeObject() ) );
existingJsonArray.unshift(myArr);
Please notice that JSON is the string representation of objects - and not suited well for manipulating them.
var array = [], // an Array literal in JavaScript code
formObject;
formObject = $('#myForm').serializeObject(); // an object representing the form
array.unshift([formObject]); // not sure why you need the nested array
// create string containing JSON representation of the array:
var jsonString = JSON.stringify(array);
For example I have the following code:
localStorage["screenshots"] = new Array();
localStorage["screenshots"]["a"] = 9;
alert(localStorage["screenshots"]["a"]);
Arr = new Array();
Arr["screenshots"] = new Array();
Arr["screenshots"]["a"] = 9;
alert(Arr["screenshots"]["a"]);
(I use Google Chrome v9.0.597.107 on Windows Vista 32-bit)
But only the second part works (output of alert() is "a")!
The first alert outputs in contrast "undefined"!
What is the problem?
Thanks.
localStorage stores values as strings, so you need to JSON serialize your objects on the way in and deserialize them on the way out. For example:
var data = {'A': 9};
localStorage['screenshots'] = JSON.stringify(data);
// Later/elsewhere:
var data = JSON.parse(localStorage['screenshots']);
// 9
console.log(data.A);
The localStorage object can only store strings. To store other types of data, use must convert them to strings, and convert them back on retrieval. In most cases you would want to use JSON to do this.
Local storage only stores string keys and string values.
The DOM Storage mechanism is a means through which string key/value pairs can be securely stored and later retrieved for use.
Source: MDC.