Convert String Array Representation Back to an Array

Convert string array representation back to an array

Just use JSON.parse('["item1", "item2", "item3"]');

Converting string representation of an array back to array

One way of transforming that string into an array of objects:

let string = "[name = preload cacheHits = 30 onDiskHits = 4 inMemoryHits = 26 misses = 0 size = 2913 averageGetTime = 0.1 evictionCount = 0 ]\n[  name = information cacheHits = 0 onDiskHits = 0 inMemoryHits = 0 misses = 0 size = 0 averageGetTime = 0.0 evictionCount = 0 ]"
console.log( string // split items by newline .split('\n') // map each item to an object .map(item => Object.fromEntries( // word characters followed by equal sign followed by word characters item.match(/\w+\s*=\s*\w+/g) // split by equal sign and trim each part .map(entry => entry.split('=').map(part => part.trim())) )));

Converting string representation of JavaScript array to object

What you're looking for is JSON.parse(). It'll take any string that represents a valid JavaScript object in JSON (JavaScript Object Notation), and convert it to an object.

var some_string = "[1,2,3,4]";
var some_array = JSON.parse(some_string);
some_array.length // Returns 4.

convert an array like looking string into array in Javascript

Replace the single quotes to double quotes, and convert to array with JSON.parse():

var str = "['Asian', 'Japanese', 'Vegetarian Friendly', 'Vegan Options', 'Gluten Free Options ']"
var result = JSON.parse(str.replace(/'/g, '"'))
console.log(result)

Converting a string representation of an array to an actual array in python

For the normal arrays, use ast.literal_eval:

>>> from ast import literal_eval
>>> x = "[1,2,3,4]"
>>> literal_eval(x)
[1, 2, 3, 4]
>>> type(literal_eval(x))
<type 'list'>
>>>

numpy.array's though are a little tricky because of how Python renders them as strings:

>>> import numpy as np
>>> x = [[1,2,3], [4,5,6]]
>>> x = np.array(x)
>>> x
array([[1, 2, 3],
[4, 5, 6]])
>>> x = str(x)
>>> x
'[[1 2 3]\n [4 5 6]]'
>>>

One hack you could use though for simple ones is replacing the whitespace with commas using re.sub:

>>> import re
>>> x = re.sub("\s+", ",", x)
>>> x
'[[1,2,3],[4,5,6]]'
>>>

Then, you can use ast.literal_eval and turn it back into a numpy.array:

>>> x = literal_eval(x)
>>> np.array(x)
array([[1, 2, 3],
[4, 5, 6]])
>>>

How we can convert an string of array to Array in JavaScript?

Use JSON.parse to parse an string into an array/object

let myArray = JSON.parse(input)

Convert string representation of array back to int array in java

So if your line is

[10, 22, 30, 55, 10, 20, 19]

then you can do

line = line.replace ("[", "");
line = line.replace ("]", "");

then you can use String.split

String vals [] = line.split (",");

then for each val you can use

intVal [x] = Integer.valueOf (val[x].trim ());


Related Topics



Leave a reply



Submit