在javascript中将字符串数组转换为数组 [英] Convert string array to array in javascript
本文介绍了在javascript中将字符串数组转换为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我从我的 django-rest-framework api 调用中得到以下项目:
I get the following item back from my django-rest-framework api call:
services = "['service1', 'service2', 'service3']"
我想要 services = ['service1', 'service2', 'service3']
在我的 JavaScript 中,我尝试了 services = JSON.parse(services)
- 什么都没做,也试过 $.parseJSON(services)
.
In my JavaScript I tried services = JSON.parse(services)
- didn't do anything, also tried $.parseJSON(services)
.
在我的序列化程序中,我尝试将设置服务设为 ListField
,也尝试过 JSONSerializerField()
In my serializers I have tried the setting services as ListField
, also tried JSONSerializerField()
class JSONSerializerField(serializers.Field):
# Adapted from http://stackoverflow.com/a/28200902
def to_internal_value(self, data):
return json.loads(data)
def to_representation(self, value):
return value
推荐答案
要解析它,您需要使用双引号而不是单引号.
To parse it you need to use double quotes instead of single.
这应该有效:
services = '["service1", "service2", "service3"]'
JSON.parse(services)
这篇关于在javascript中将字符串数组转换为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文