Convert Javascript string or array into JSON object

I have a JavaScript variable with comma separated string values - ie 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!!

链接地址: http://www.djcxy.com/p/47834.html

上一篇: 使用Jquery和Json登录认证

下一篇: 将JavaScript字符串或数组转换为JSON对象