Split object in Node.js - javascript

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);

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 convert a string representation of date array to array JS?

I need to convert a string representation of array to JS array for looping purpose
the string is single quoted
in My js
var length1 = $('.length').text(); //['2018-9-24', '2018-9-26', '2018-9-25']
console.log(length1.length) // 39 as output i need it as 3
to loop through each date
Any help would be appreciated
I tried
var myArray=json.parse(length1) // but its not working
Replace single quotes with double and then parse it:
var str = "['2018-9-24', '2018-9-26', '2018-9-25']";
console.log(JSON.parse(str.replace(/'/g, '"')));
I had done this in an another way
var objectstring = "['2018-9-24', '2018-9-26', '2018-9-25']";
var objectStringArray = (new Function("return [" + objectstring+ "];")());

JSON.parse() returns a string instead of object

I'd hate to open a new question even though many questions have been opened on this same topic, but I'm literally at my ends as to why this isn't working.
I am attempting to create a JSON object with the following code:
var p = JSON.stringify(decodeJSON('{{post.as_json}}'))
var post = JSON.parse(p);
console.log(post); // Debug log to test if code is valid
And the decodeJSON function:
function decodeJSON(json) {
var txt = document.createElement("textarea");
txt.innerHTML = json;
return txt.value.replace(/u'/g, "'");
}
console.log(post) returns the following JSON string:
{'content': 'kj fasf', 'uid': '4eL1BQ__', 'created': '07/09/2017', 'replies': [], 'tags': ['python'], 'by': {'username': 'Dorian', 'img_url': '/static/imgs/user_Dorian/beaut.jpg'}, 'likes': 0}
After scanning through the string I am pretty sure that the JSON is valid and there are no syntax errors. However, when running JSON.parse(p) Instead of receiving an object, I get a string back. What could be the cause?
That's because decodeJSON returns a string, and JSON.stringify turns that string in another string.
In the other hand, you used JSON.strigify() method on a string. You should stringify an object, not string.
JSON.stringify() turns a javascript object to json text and stores it
in a string.
When you use JSON.parse you obtain the string returned by decodedJSON function, not object.
Solution:
var p = JSON.stringify('{{post.as_json}}');
var post = JSON.parse(p);
console.log(post);
It gives me Uncaught SyntaxError: Unexpected token ' in JSON at
position 1
The solution is to modify your decodeJSON method.
function decodeJSON(json) {
var txt = document.createElement("textarea");
txt.innerHTML = json;
return txt.value.replace(/u'/g, '\"');
}
var p = decodeJSON('{{post.as_json}}');
var post = JSON.parse(p);
console.log(post);
The issue in your code is that you are performing JSON.stringify on a string itself. So on parsing the result of this string will be a string. In effect, you have stringified twice and parsed once. If you parse it once more you will get a JSON. But for solution avoid the stringification twice.
Replace in your code.
var p = decodeJSON('{{post.as_json}}');
That will work

Convert string (looking like array) to multidimensional array

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]')

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));
});

Categories

Resources