如何在JavaScript中将字符串转换为数组

时间:2020-06-15 05:42:31

标签: javascript

我正在使用高级图表构建图表。我的系列数据来自数据库,通过MVC中的控制器。我将输出存储在字符串变量中。我需要将此字符串变量转换为Array对象。请帮我做。我的字符串变量输出是

package com.example.myfirstapp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class DisplayMessageActivity extends AppCompatActivity {

    public  TextView textView = findViewById(R.id.textView);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_display_message);
    }

     // Get the Intent that started this activity and extract the string
     Intent intent = getIntent();
     String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);

     // set the string as its text

     textView.setText(message);

}

我尝试使用JSON.parse和$ .parseJSON命令,但无法正常工作。它给我的错误是“ SyntaxError:JSON.parse:预期属性名称或'}'在JSON数据的第1行第2列” 有人可以帮助我解决问题。自最近5天以来,我一直为此感到困惑。

1 个答案:

答案 0 :(得分:0)

许多人提到的问题是您没有有效的JSON字符串。您需要修复三件事。

  1. 将变量名括在引号中。
  2. 删除数据值中的逗号。
  3. 将整个内容包装在方括号中。

最后,您的JSON字符串应如下所示:

[{"name": "2019","data":[3883,3961,3893,3780,4021,3765,3560,4099,3310,3403,3628,3137]},{"name": "2020","data":[3489,3883,3403,3331,2605,1546]}]

一旦您可以产生一个看起来像有效JSON的字符串,就可以使用JSON.parse()方法来产生一个可迭代的对象。像这样:

var myJSON = JSON.parse('[{"name": "2019","data":[3883,3961,3893,3780,4021,3765,3560,4099,3310,3403,3628,3137]},{"name": "2020","data":[3489,3883,3403,3331,2605,1546]}]');
相关问题