简体   繁体   English

如何将字符串转换为数组?

[英]how can I convert the string to array?

I would like to convert the long-string to an array to access detail inside.我想将长字符串转换为数组以访问内部的详细信息。 In my case, the string is like below就我而言,字符串如下所示

'[{"timestamp": 1567814400033, "fair_value": 0.01641267}, {"timestamp": 1567814400141, "fair_value": 0.01641273}]'

Desired result would be single array where contain dicts inside like this所需的结果将是单个数组,其中包含这样的字典

[{"timestamp": 1567814400033, "fair_value": 0.01641267}, {"timestamp": 1567814400141, "fair_value": 0.01641273}]

Thank for your help!感谢您的帮助!

Try this:尝试这个:

import json

array = '[{"timestamp": 1567814400033, "fair_value": 0.01641267}, 
         {"timestamp": 1567814400141, "fair_value": 0.01641273}]'
data  = json.loads(array)
print (data)

Output: Output:

在此处输入图像描述

I have solve this case by myself by using ast.literal_eval() lib我已经通过使用 ast.literal_eval() lib 自己解决了这个问题

You would be needing to import literal_eval from ast module of python, it is a standard package installed in python which stands for Abstract Syntax Trees , more info here: https://docs.python.org/2/library/ast.html You would be needing to import literal_eval from ast module of python, it is a standard package installed in python which stands for Abstract Syntax Trees , more info here: https://docs.python.org/2/library/ast.html

Your code will look something like this:您的代码将如下所示:

from ast import literal_eval
your_variable = literal_eval('[{"timestamp": 1567814400033, "fair_value": 0.01641267}, {"timestamp": 1567814400141, "fair_value": 0.01641273}]')

I hope this helps!我希望这有帮助!

Use the python json library .使用 python json 库 You can use it to parse your strings to json and also stringfy your dictionary or arrays .您可以使用它将您的字符串解析为 json 并字符串化您的dictionaryarrays

import json

# Convert string to python object
data = json.loads(<JSON_STRING>)

# Stringfy python dictionary or array
string_data = json.dumps(<PYTHON_OBJECT>)

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

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