How can we convert the following string into a list and vice versa in c#?
String1: "['hello', 'world', 100, 12.59, [1, '2', ['3', 4, {'key': 'value'}]]]"
Expected List1: ['hello', 'world', 100, 12.59, [1, '2', ['3', 4, {'key': 'value'}]]]
Expected results:
Console.WriteLine(List1[0]) //Output: 'hello'
Console.WriteLine(List1[4][2][1]) //Output: 4
Console.WriteLine(List1[4][2][2]['key']) //Output: 'value'
Note:
In python, we have an eval(expression) method to convert the string into a list.
we have a repr(obj) method to convert the list back into a string.
Please refer to the below sample code using python methods. I require similar methods in c#.
>>> str1="['hello', 'world', 100, 12.59, [1, '2', ['3', 4, {'key': 'value'}]]]"
>>> list1=list(eval(str1))
>>> list1
['hello', 'world', 100, 12.59, [1, '2', ['3', 4, {'key': 'value'}]]]
>>> list1[4][2][2]['key']
'value'
>>> list1[4][2][0]
'3'
>>> str2=repr(list1)
>>> str2
"['hello', 'world', 100, 12.59, [1, '2', ['3', 4, {'key': 'value'}]]]"
Each and every solution will be appreciated.
Thanks!!!
You can use Newtonsoft.Json
library to achieve that. You need to deserialize the string as a JArray
, as follows:
public static void Main()
{
var arr = "['hello', 'world', 100, 12.59, [1, '2', ['3', 4, {'key': 'value'}]]]";
var parsed = JsonConvert.DeserializeObject<JArray>(arr);
Console.WriteLine(parsed[4][2][2]["key"]);
}
You can see a live demo here.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments