parse multiple json string into one object in javascript - javascript

I have a json output where it gets two strings with format such as
[{"device_id":"9700015","update_time":"2017-01-04 18:30:00","sensor_value":"1287.6"}]
[{"device_id":"9700016","update_time":"2016-12-31 18:30:00","sensor_value":"1113.8"}]
I want to parse these strings into one object. I have used the JSON.parse(data) but its giving me first string in object and not the all strings. How do I achieve this.
i want the output should be
[{"device_id":"9700015","update_time":"2017-01-04 18:30:00","sensor_value":"1287.6"},
{"device_id":"9700016","update_time":"2016-12-31 18:30:00","sensor_value":"1113.8"}]

I guess you'd want an array with both of the objects inside, otherwise, please specify what is your expected output.
If you are unable to modify the JSON string received to make it look like a proper array, I'd substitute the '][' for a comma ',' so you can parse the JSON string and receive back an array with two objects inside, like so:
original = '[{"device_id":"9700015","update_time":"2017-01-04 18:30:00","sensor_value":"1287.6"}][{"device_id":"9700016","update_time":"2016-12-31 18:30:00","sensor_value":"1113.8"}]';
replaced = original.replace('][', ',');
parsed = JSON.parse(replaced);
Edited:
Just in case your input contains a line break between the closing and opening square brackets, your substitution should be like that:
replaced = original.replace(']\n[', ',');
2nd edit:
If your input contains more than two lines like these, there is no problem, your replace call will substitute every one of the matches if you write it like that:
replaced = original.replace(/\]\[/g, ',');
This is a regular expression that substitutes every occurence of ][ (expressed as \]\[ because these are special characters for regular expressions), with the help of the global flag specified at the end of the regular expression.

You can do:
var obj1 = [{"device_id":"9700015","update_time":"2017-01-04 18:30:00","sensor_value":"1287.6"}]
var obj2 = [{"device_id":"9700016","update_time":"2016-12-31 18:30:00","sensor_value":"1113.8"}]
/* or */
var obj1 = JSON.parse('[{"device_id":"9700015","update_time":"2017-01-04 18:30:00","sensor_value":"1287.6"}]')
var obj2 = JSON.parse('[{"device_id":"9700016","update_time":"2016-12-31 18:30:00","sensor_value":"1113.8"}]')
// then flatten into one array
var combined = [].concat.apply([], [obj1, obj2])
console.log(combined);
// [{"device_id":"9700015","update_time":"2017-01-04 18:30:00","sensor_value":"1287.6"}, {"device_id":"9700016","update_time":"2016-12-31 18:30:00","sensor_value":"1113.8"}]

Related

Obtain arguments from a string seperated by a space and convert an argument in an array format to an array

I have arguments that will be passed by the user for a command. Each argument for a command will be seperated with a space, which will represent a new argument. Example: "arg1 arg2 arg3" converts to ["arg1", "arg2", "arg3"] where the output is a JS array. This can be done with a simple .split(" ").
However, my problem begin when trying to format an array as a command argument. My goal is to allow the user to enter an agument in the format of an array (e.g. Starts with [ may contain multiple elements seperated by a , and ends with a ]) so for example: "arg1 [elem1, elem2] arg3" converts to ["arg1", ["elem1", "elem2"], "arg3"] where the inner and outer array is a JS array.
I have tried using JSON.Parse() however, each element would require the user to have " at the start of each element which is too complex for the user and non essential to be inputting. Also, the elements may not always intend to be a string and may be Boolean, Number or a custom type.
As of currently, this has been my best solution but misses some requirements and also is non functional when an array has a space inside.
s.split(/[\[\]]|\s+/).filter(arg => arg.length > 1);
I have come up with some other solutions but all are missing one thing or another in the required specification set above. A solution that can handle nested arrays would be nice however it is non-essential and could make the solution alot more complex than it needs to be.
Let's assume no funny characters as the input. Also nesting not allowed.
var str = "arg1 [ elem1 , elem2,elem3 ] arg3";
console.log(str)
// removing white spaces from the [ array ]
str = str.replace(/\s*,\s*/g, ',');
str = str.replace(/\[\s*/g, '[');
str = str.replace(/\s*\]/g, ']');
// now split on words
var arr = str.split(/\s+/);
arr = arr.map(function(elem) {
// if begins with [ it is assumed to be an array to be splitted
return elem.charAt(0) == '[' ? elem.slice(1, -1).split(",") : elem;
})
console.log(arr)

Why is the first match empty when using a split regex? [duplicate]

I don't understand this behaviour:
var string = 'a,b,c,d,e:10.';
var array = string.split ('.');
I expect this:
console.log (array); // ['a,b,c,d,e:10']
console.log (array.length); // 1
but I get this:
console.log (array); // ['a,b,c,d,e:10', '']
console.log (array.length); // 2
Why two elements are returned instead of one? How does split work?
Is there another way to do this?
You could add a filter to exclude the empty string.
var string = 'a,b,c,d,e:10.';
var array = string.split ('.').filter(function(el) {return el.length != 0});
A slightly easier version of #xdazz version for excluding empty strings (using ES6 arrow function):
var array = string.split('.').filter(x => x);
This is the correct and expected behavior. Given that you've included the separator in the string, the split function (simplified) takes the part to the left of the separator ("a,b,c,d,e:10") as the first element and the part to the rest of the separator (an empty string) as the second element.
If you're really curious about how split() works, you can check out pages 148 and 149 of the ECMA spec (ECMA 262) at http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf
Use String.split() method with Array.filter() method.
var string = 'a,b,c,d,e:10.';
var array = string.split ('.').filter(item => item);
console.log(array); // [a,b,c,d,e:10]
console.log (array.length); // 1
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/split
trim the trailing period first
'a,b,c,d,e:10.'.replace(/\.$/g,''); // gives "a,b,c,d,e:10"
then split the string
var array = 'a,b,c,d,e:10.'.replace(/\.$/g,'').split('.');
console.log (array.length); // 1
That's because the string ends with the . character - the second item of the array is empty.
If the string won't contain . at all, you will have the desired one item array.
The split() method works like this as far as I can explain in simple words:
Look for the given string to split by in the given string. If not found, return one item array with the whole string.
If found, iterate over the given string taking the characters between each two occurrences of the string to split by.
In case the given string starts with the string to split by, the first item of the result array will be empty.
In case the given string ends with the string to split by, the last item of the result array will be empty.
It's explained more technically here, it's pretty much the same for all browsers.
According to MDN web docs:
Note: When the string is empty, split() returns an array containing
one empty string, rather than an empty array. If the string and
separator are both empty strings, an empty array is returned.
const myString = '';
const splits = myString.split();
console.log(splits);
// ↪ [""]
Well, split does what it is made to do, it splits your string. Just that the second part of the split is empty.
Because your string is composed of 2 part :
1 : a,b,c,d,e:10
2 : empty
If you try without the dot at the end :
var string = 'a,b,c:10';
var array = string.split ('.');
output is :
["a,b,c:10"]
You have a string with one "." in it and when you use string.split('.') you receive array containing first element with the string content before "." character and the second element with the content of the string after the "." - which is in this case empty string.
So, this behavior is normal. What did you want to achieve by using this string.split?
try this
javascript gives two arrays by split function, then
var Val = "abc#gmail.com";
var mail = Val.split('#');
if(mail[0] && mail[1]) { alert('valid'); }
else { alert('Enter valid email id'); valid=0; }
if both array contains length greater than 0 then condition will true

How to split a comma separated list in javascript, but do not split anything inside quotes with null values

I have a comma separated list that could contain blank values, and could contain values wrapped in double-quotes that I do not want to split. I need to create an array using this split so that I can later loop through it.
I've tried using some match regex which works, except it overlooks any null values that I have. I've been trying to use some look ahead regex but I don't think my syntax is working appropriately, as it's returning an array with a length of 1.
This is the match code that most closely shows what I'm going for
var s = 'To, Infinity, "And, Beyond",,Buzz Lightyear';
var array = s.match(/(".*?"|[^",\s]+)(?=\s*,|\s*$)/g);
This is the split syntax which is only returning an array length of 1
var s = 'To, Infinity, "And, Beyond",,Buzz Lightyear';
var array = s.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
With the match function, I expect the output to be:
To
Infinity
And, Beyond
Buzz Lightyear
However, my output is actually
To
Infinity
And, Beyond
Buzz Lightyear
Since you tagged mirth in your question, you can use the built in mirth parser. Note that your exact string from your question won't work because there is a space after the comma and before "And, Beyond." If you are going to quote a CSV field, the entire field needs to be quoted (otherwise the quote is seen as part of the value.)
var serializer = SerializerFactory.getSerializer('delimited');
var s = 'To,Infinity,"And, Beyond",,Buzz Lightyear';
var split = new XML(serializer.toXML(s));
for each (var col in split.row.children()) {
logger.info(col.toString());
}
Edit: I did not produce an array, since you said you only needed it for looping, which is shown above, but if you still need an array you can do:
var arr = [];
for each (var col in split.row.children()) {
arr.push(col.toString());
}
This should work as per your expectation:
var s = 'To, Infinity, "And, Beyond",,Buzz Lightyear';
var array = s.split(/,(?=(?:(?:[^"]*"){2})*[^"]*$)/);
console.log(array);

How could one split a comma delimited string while ignoring the commas which are in braces?

I have a string which represents the attributes of a function:
str = "'MyCommunities', null, {'viewAllLink':'https://cpkornferrybruceapidev.azurewebsites.net', 'clientId':'078c49af-bb40-44c3-a685-539a84cc5de7', 'subscriptionId':'64fc6f58-2a67-472b-b57f-f0f5441e7992'}"
There are 3 attributes: My Communities, null, {...}
I would like to split the string into array containing these 3 values but without splitting the object literal.
I believe I need to construct a regular expression which would allow me to str.split(//) however I am not able to get the 3 attributes which I need.
Any help would be appreciated.
If be sure the string doesn't have extra ' in the value of each element, I think one quick way is treat it as one JSON string, then pull out the element you need.
The codes are like below:
let str = "'MyCommunities', null, {'viewAllLink':'https://cpkornferrybruceapidev.azurewebsites.net', 'clientId':'078c49af-bb40-44c3-a685-539a84cc5de7', 'subscriptionId':'64fc6f58-2a67-472b-b57f-f0f5441e7992'}"
console.log(JSON.parse('[' + str.replace(/'/g, '"') +']'))
If you don't have nested braces and if comma is always before {, then you can do this:
var re = /(\{[^}]+\})/;
var result = [];
str.split(re).forEach(function(part) {
if (part.match(re) {
result.push(part);
} else {
var parts = part.split(',').map((x) => x.trim()).filter(Boolean);
result = result.concat(parts);
}
});
if you have something before braces or if braces are nested you will need more compicated parser.
My first suggestion would be to find a different way to get the string formatted coming into your system. If that is not feasible, you can do the following regex (note: it is super fragile):
/\,(?![^{]*})/
and get the groupings like so:
list = str.split(/\,(?![^{]*})/)
I would use the second limit parameter of split() (docs) to stop cutting before the object literal:
var str = "'MyCommunities', null, {'viewAllLink':'https://cpkornferrybruceapidev.azurewebsites.net', 'clientId':'078c49af-bb40-44c3-a685-539a84cc5de7', 'subscriptionId':'64fc6f58-2a67-472b-b57f-f0f5441e7992'}";
console.log(str.split(', ', 3));

javascript: get everything after certain characters from a string?

I'm trying to get everything after certain characters in a string.
But I have no idea why with my, when I alert(); the result, there is a comma before the string!
Here is a working FIDDLE
And this is my code:
var url = "mycool://?string=mysite.com/username_here80";
var urlsplit = url.split("mycool://?string=");
alert(urlsplit);
any help would be appreciated.
Split separates the string into tokens separated by the delimiter. It always returns an array one longer than the number of tokens in the string. If there is one delimiter, there are two tokens—one to the left and one to the right. In your case, the token to the left is the empty string, so split() returns the array ["", "mysite.com/username_here80"]. Try using
var urlsplit = url.split("mycool://?string=")[1]; // <= Note the [1]!
to retrieve the second string in the array (which is what you are interested in).
The reason you are getting a comma is that converting an array to a string (which is what alert() does) results in a comma-separated list of the array elements converted to strings.
The split function of the string object returns an Array of elements, based on the splitter. In your case - the returned 2 elements:
var url = "http://DOMAIN.com/username_here801";
var urlsplit = url.split("//");
console.log(urlsplit);
The comma you see is only the representation of the Array as string.
If you are looking for to get everything after a substring you better use the indexOf and slice:
var url = "http://DOMAIN.com/username_here801";
var splitter = '//'
var indexOf = url.indexOf(splitter);
console.log(url.slice(indexOf+splitter.length));
I'd use a simple replace..
var s = "mycool://?string=mysite.com/username_here80";
var ss = s.replace("mycool://?string=", "");
alert(ss);

Categories