简体   繁体   English

将Javascript字符串或数组转换为JSON对象

[英]Convert Javascript string or array into JSON object

I have a JavaScript variable with comma separated string values - ie value1,value2,value3, ......,valueX, 我有一个逗号分隔字符串值的JavaScript变量 - 即value1,value2,value3, ......,valueX,

I need to convert this variable's values into a JSON object. 我需要将此变量的值转换为JSON对象。 I will then use this object to match user enteredText value by using filterObj.hasOwnProperty(search) 然后我将使用此对象通过使用filterObj.hasOwnProperty(search)匹配用户的enteredText值

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. 您似乎想要的是从您的字符串构建一个JavaScript对象,该对象将充当地图,以便您可以有效地测试内部的值。

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? 为何选择JSON? You can convert it into an array with split(",") . 您可以将其转换为具有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. 使用array[i]访问它应该可以完成这项工作。

for (var i = 0; i < array.length; i++) {
    // do anything you want with array[i]
}

JSON is used for data interchanging. JSON用于数据交换。 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进行处理时,不需要JSON。

JavaScript has JSON.stringify() method to convert an object into JSON string and similarly JSON.parse() to convert it back. JavaScript有JSON.stringify()方法将对象转换为JSON字符串,类似JSON.parse()将其转换回来。 Read more about it 阅读更多相关信息

All about JSON : Why & How 关于JSON:为什么和如何

Cheers!! 干杯!!

JSON format requires (single or multi-dimensional) list of key, value pairs. JSON格式需要(单维或多维)键,值对列表。 You cannot just convert a comma separated list in to JSON format. 您不能只将逗号分隔列表转换为JSON格式。 You need keys to assign. 您需要分配密钥。

Example, 例,

[
  {"key":"value1"},
  {"key":"value2"},
  {"key":"value3"},
  ...
  {"key":"valueX"}
]

I think for your requirement, you can use Array. 我认为根据您的要求,您可以使用Array。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM