Convert string (looking like array) to multidimensional array - javascript

I have a string:
[[-3.9,-160.1,34.7],[-0.4,16.3,18.0],[236,236,231],'SMTH 123',35]
How I can convert it to a multidimensional array?

You can use JSON.parse() to convert a string into an object, assuming it's valid JSON to begin with. Your data has strings delimited by single quotes, which is not valid JSON. If you replace them with double quotes then it will work...
var s = "[[-3.9,-160.1,34.7],[-0.4,16.3,18.0],[236,236,231],'SMTH 123',35]";
var ar = JSON.parse(s.split("'").join("\""));
console.log(ar);

How about doing something like this:
function stringToObject(data) {
var converted = {};
try {
converted = JSON.parse(data);
} catch(err) {
console.log('Provided data is not valid', err);
}
return converted;
}
console.log(stringToObject('[[-3.9,-160.1,34.7],[-0.4,16.3,18.0],[236,236,231],"SMTH 123",35]'));
console.log(stringToObject('[[-3.9,-160.1,34.7],[-0.4,16.3,18.0],[236,236,231')); // invalid string
Notice that I have changed ' into " in my sample if that is a problem you may take a look at conversion done in another answer for that question.

Assuming JQuery is also okay:
var arr = $.parseJSON('[[-3.9,-160.1,34.7],[-0.4,16.3,18.0],[236,236,231],'SMTH 123',35]')

Related

How change a string looks like array to a real aray

I have a string, it looks like a array but not a real array. So my question is how to make it to a real array.
let string = "["abc", "cde"]";
// how to make string become an array
change string to an array
First you need to make sure your string is invalid format
"["abc", "cde"]" // invalid
"[abc, cde]" // invalid
"[11, 22]" // valid,if you do not want to use quote to wrap it,then the elements need to be number
"['abc', 'cde']" // valid
let string = `["abc", "cde"]`
const array = JSON.parse(string)
console.log(array)
You can do something like this
let data = "['abc', 'pqr', 'xxx']";
data = data.replace(/'/g, '"');
console.log(data)
const convertedArray = JSON.parse(data);
console.log(convertedArray)
Observation : Your input string is not a valid JSON string.
Solution : Double quotes besides the array items should be escaped to parse it properly. Your final string should be.
let string = "[\"abc\", \"cde\"]";
Now you can parse it using JSON.parse() method.
Live Demo :
let string = "['abc', 'cde']";
string = string.replace(/'/g, '"');
console.log(string); // "[\"abc\", \"cde\"]"
console.log(JSON.parse(string)); // ["abc", "cde"]

How to decode in JavaScript/Node.js a string of combined UTF16 and normal characters?

I have a huge JSON stringified into a string like this one:
"\\u007B\\u0022name\\u0022\\u003A\\u0022T\\u0065st\\u0022}"
I need to JSON.parse it to use as an object. Do you know any way to decode it?
I tried decodeURIComponent(), unescape(), different variants of .replace( /\\u/g, "\u" ) and I can not get it into the needed form.
You can convert UTF-16 to text using the following function:
function utf16ToText(s) {
return s.replace(/\\u[0-9a-fA-F]{4}/gi, match => {
return String.fromCharCode(parseInt(match.replace(/\\u/g, ""), 16));
});
}
Demo:
const r = utf16ToText("\\u007B\\u0022name\\u0022\\u003A\\u0022T\\u0065st\\u0022\\u007d");
console.log("As text: ", r);
const j = JSON.parse(r);
console.log("As JSON: ", j);
console.log("JSON Prop: ", j.name);
function utf16ToText(s) {
return s.replace(/\\u[0-9a-fA-F]{4}/gi, match => {
return String.fromCharCode(parseInt(match.replace(/\\u/g, ""), 16));
});
}
If your string is valid JSON, then you can use JSON.parse() to process the UTF16 for you. To make what you have valid JSON, you have to add double quotes to each end (inside the actual string) as all strings must be enclosed in double quotes in the JSON format. Here's an example:
let data = "\\u007B\\u0022name\\u0022\\u003A\\u0022T\\u0065st\\u0022\\u007d";
// to make this legal JSON so we can let the JSON parser parse it for us and
// handle the UTF16 for us, we need to put double quotes in the actual string at each end
// Then, it's legal JSON and we can parse it
let str = JSON.parse('"' + data + '"');
console.log(str);
console.log("type is", typeof str);
This gives you a result in string form:
{"name":"Test"}
This result is now legal JSON on its own. If you then wanted to parse that as JSON, could just call JSON.parse() on it again to turn it into an actual Javascript object:
let data = "\\u007B\\u0022name\\u0022\\u003A\\u0022T\\u0065st\\u0022\\u007d";
let str = JSON.parse('"' + data + '"'); // decoded string here
// now take the string and actually parse it into a Javascript object
let obj = JSON.parse(str);
console.log(obj); // Javascript object here
console.log("type is", typeof obj);
This gives you a resulting live Javascript object:
{name:"Test"}
The first call to JSON.parse() just takes your JSON string and decodes it into a Javascript string. Since that Javascript string is now also legal JSON for an object definition, you can call JSON.parse() on it again to turn it into a Javascript object.
Thank you for your input. Because of that, I got the solution:
let a = "\\u007B\\u0022name\\u0022\\u003A\\u0022T\\u0065st\\u0022}" original string
let b = '"' + a + '"' adding " in order to make a valid stringified JSON
let c = JSON.parse(b) that will produce a partially decoded string (partially because some of the \uXXXX characters can stay in the string)
let solution = JSON.parse(c) that will create an object with all the characters decoded
Big thanks to #jfriend00

Split object in Node.js

Yesterday i solve my problem spliting my string with "\" but today i have the same problem but with a object...
2|wscontro | [2017-05-31 15:57:23.145] - debug: /opt/wscontroller/wscontroller-api/routes/ubus UbusController 63320169-611e-43f5-880e-9b1a13152cfd getDeviceServicesById signature {"config":"wireless","section":"radio0","values":"{\"disabled\":0}"}
2|wscontro | [2017-05-31 15:57:23.145] - debug: /opt/wscontroller/wscontroller-api/routes/ubus UbusController 63320169-611e-43f5-880e-9b1a13152cfd getDeviceServicesById signature "object"
I need to have only signature =>
{"config":"wireless","section":"radio0","values":{"disabled":0"}}
Can anyone help me? I try to convert to String this object and split doing
var aux = signature.split('\\').join('');
var jsonObject = JSON.parse(aux);
But i get the same result {"config":"wireless","section":"radio0","values":"{\"disabled\":0"}}
My last post: Split string by "\" Node.js
anyone can help?
is this you wanted?
var str =' {"config":"wireless","section":"radio0","values":"{\"disabled\":0"}';
console.log(str.replace(/\\/g,''));
Your object should be like you said in your last comment {"config":"wireless","section":"radio0","values":"{\"disable‌​d\":0}"} then:
var jsonstring = "{"config":"wireless","section":"radio0","values":"{\"disable‌​d\":0}"}";
var escapedJsonstring = jsonstring.split('\\').join('');
var json = JSON.parse(escapedJsonstring);
json.parsedValues = JSON.parse(json.values);
console.log(json);
Finally you have parsed object in json variable. The main idea is that the values attribute has also string value and not object value. So you need to parse it again as JSON. Result of this parsing is stored in json.parsedValues, but you can rewrite the values string with object using this: json.values = JSON.parse(json.values);

Converting int array in string format to array

I have an array of integers stored in string format.
eg:
"[3,2,1]"
How can I convert this to an actual array?
I've searched high and low for a simple solution but I can't seem to find it.
Passing the string into JSON.parse and $.parseJSON results in "[" being shown for the 0 index. So I'm assuming it's not doing anything.
var arr = JSON.parse("[3,2,1]")
var text = "[3,2,1]";
var obj = JSON.parse(text);
console.log(obj);
You could use jQuery $.parseJSON() method :
var arr = $.parseJSON("[3,2,1]");
var str = "[3,2,1]";
console.log( $.parseJSON(str) );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Or pure javascript method JSON.parse() :
var arr = JSON.parse("[3,2,1]");
Hope this helps.
var str = "[3,2,1]";
console.log( JSON.parse("[3,2,1]") );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
So I've figured out I needed to slice the first and last characters off as for some reason the string was being returned as ""[3,2,1]"" rather than "[3,2,1]" even though it's stored without quotes.
From your updated description it appears you have a string that starts and ends with ", so a simple JSON.parse will not work, since that will just convert what's between the "'s to a string. You need to either JSON.parse twice, since you have an array of integers embedded in a string, or manually parse.
JSON.parse twice way:
var str = '"[3,2,1]"';
var parsedStr = JSON.parse(str); // results in a string with contents [3,2,1]
var intArray = JSON.parse(parsedStr); // results in an int array with contents [3,2,1]
Or, if format could change to be non-JSON at some point, manual way:
var str = '"[3,2,1]"';
var intArray = [];
str.substr(2,str.length-3).split(/,/g).forEach(function(numStr) {
intArray.push(parseInt(numStr));
});

How to Convert Array-like String to Array

I have a string that looks like an array: "[918,919]". I would like to convert it to an array, is there an easier way to do this than to split and check if it is a number? Thanks
Use JSON.parse.
var myArray = JSON.parse("[918,919]");
You can get rid of the brackets at the beginning and the end, then use:
str.split(",")
which will return an array split by the comma character.
EDIT
var temp = new Array();
temp = "[918,919]".slice( 1, -1).split(",");
for (a in temp ) {
temp[a] = parseInt(temp[a]);
}
If you use JSON.parse the string must have " and not ' otherwise the code will fail.
for example:
let my_safe_string = "['foo','bar',123]";
let myArray = JSON.parse(my_safe_string)
the code will fail with
Uncaught SyntaxError: Unexpected token ' in JSON at position 1
instead if you use " all will work
let my_safe_string = "["foo","bar",123]";
let myArray = JSON.parse(my_safe_string);
so you have two possibility to cast string array like to array:
Replace ' with " my_safe_string.replace("'",'"'); and after do JSON.parse
If you are extremely sure that your string contain only string array you can use eval:
example:
let myArray = eval(my_safe_string );

Categories

Resources