-2

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"}]
amol desai
  • 237
  • 1
  • 6
  • 14

2 Answers2

0

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.

0

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"}]
riyaz-ali
  • 8,677
  • 2
  • 22
  • 35