ShanN
ShanN

Reputation: 941

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!

Upvotes: 0

Views: 74

Answers (4)

Isaac Obella
Isaac Obella

Reputation: 2643

Use the python json library. You can use it to parse your strings to json and also stringfy your dictionary or arrays.

import json

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

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

Upvotes: 0

Mr.AK
Mr.AK

Reputation: 26

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!

Upvotes: 1

Lakshya Srivastava
Lakshya Srivastava

Reputation: 709

Try this:

import json

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

Output:

enter image description here

Upvotes: 3

ShanN
ShanN

Reputation: 941

I have solve this case by myself by using ast.literal_eval() lib

Upvotes: 1

Related Questions