Randy
Randy

Reputation: 3

I need to convert a specially formatted string to an javascript array

I'm trying to convert a formatted string to a JavaScript multidimensional array.

I've tried split() and push() functions but neither seem to work. The format should be already right but I can't seem to figure out how to make the string into an array.

Here's the string:

[[24297, 'CWCS Sump 002', -121.50842, 38.54798, '2', 'SEWER SUMP'],[8035, 'CWCS Sump 002A (56)', -121.50842, 38.54798, '2A', 'SEWER SUMP'],[9334, 'CWCS Sump 001', -121.5110297, 38.5703431, '1', 'SEWER SUMP']]

I just want a JavaScript array that is 3x6 (if I counted that right) from that string. The number of rows will vary.

Upvotes: 0

Views: 43

Answers (3)

dWinder
dWinder

Reputation: 11642

You can do it with JSON.parse as:

let str = '[[24297, "CWCS Sump 002", -121.50842, 38.54798, "2", "SEWER SUMP"],[8035, "CWCS Sump 002A (56)", -121.50842, 38.54798, "2A", "SEWER SUMP"]]';

let arr = JSON.parse(str);

Notice it better to have the ' around the entire string the " around the string inside. Can do that with:

str.replace("'", """);

Upvotes: 1

Vivek Jain
Vivek Jain

Reputation: 44

According to me It wont be straight forward. You can try like this.

let a = "[
    [24297,'CWCS Sump 002',-121.50842, 38.54798,'2','SEWER SUMP'],
    [8035,'CWCS Sump 002A (56)',-121.50842,38.54798,'2A','SEWER SUMP'],
    [9334,'CWCS Sump 001', -121.5110297,38.5703431,'1','SEWER SUMP']
]";
let c= [];

a.replace('[[','').replace(']]','').split('],[').forEach(
    (x)=>{c.push(x.split(','))}
);
//c is the result

Upvotes: 0

ggorlen
ggorlen

Reputation: 56865

This is a good candidate for JSON.parse; however, single quotes should be converted to double quotes before it will work. Being careful for escaped quotes, you can try:

const raw = `[[24297, 'CWCS Sump 002', -121.50842, 38.54798, '2', 'SEWER SUMP'],[8035, 'CWCS Sump 002A (56)', -121.50842, 38.54798, '2A', 'SEWER SUMP'],[9334, 'CWCS Sump 001', -121.5110297, 38.5703431, '1', 'SEWER SUMP']]`;

const res = JSON.parse(raw.replace(/(?<!\\)'/g, `"`));
console.log(res);

Upvotes: 1

Related Questions