繁体   English   中英

将数组的字符串表示形式转换为 Python 中的实际数组

[英]Convert String Representation Of Array To Actual Array In Python

我对 python 很陌生,并且正在努力完成这项工作。

我需要转换

["ladksa dlskdlsd slkd sldks lskds lskds","skkdsdl skdsl lskds lsdk sldk sdslkds"] - String Representation of Array To Actual Array Like this.

[0]-> "ladksa dlskdlsd slkd sldks lskds lskds"
[1]-> "skkdsdl skdsl lskds lsdk sldk sdslkds"

我尝试过以下事情:

json.load(array) -> but it gave me parse array error
literal_eval(x)  -> read it somewhere (dont know why it doesn't work)

错误:

custom_classes = json.loads(element.custom_classes)
 File "C:\Users\Shri\AppData\Local\Programs\Python\Python38-32\lib\json\__init_
.py", line 357, in loads
   return _default_decoder.decode(s)
 File "C:\Users\Shri\AppData\Local\Programs\Python\Python38-32\lib\json\decoder
py", line 337, in decode
   obj, end = self.raw_decode(s, idx=_w(s, 0).end())
 File "C:\Users\Shri\AppData\Local\Programs\Python\Python38-32\lib\json\decoder
py", line 355, in raw_decode
   raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 2 (char 1)

另外,我使用下面的 js 代码来发送数据:

'custom_classes':'\''+JSON.stringify(finalized_classes)+'\'',

数据存储为:请在此处查看图片

arr_element = array of Objects For Specific Class

有一个属性

custom_classes -> which is stored as above image.

我正在做:

for element in arr_element:
    string_obj = json.loads(str(element.custom_classes))
    //here it is error

请帮忙

import json

s = '["ladksa dlskdlsd slkd sldks lskds lskds","skkdsdl skdsl lskds lsdk sldk sdslkds"]'

json.loads(s)

# gives ['ladksa dlskdlsd slkd sldks lskds lskds', 'skkdsdl skdsl lskds lsdk sldk sdslkds']

After you use json.loads() , you can use str.split() to turn the strings into arrays, and then append one of the arrays onto the other if you need to.

foo = ['this is a sentence', 'this is a different sentence']

bar = foo[0].split(' ')
biz = foo[1].split(' ')

bar.append(biz)

print(bar)

结果: ['this', 'is', 'a', 'sentence', 'this', 'is', 'a', 'different', 'sentence']

暂无
暂无

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

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