0

My data is coming in following format from google spreadsheet:

Object {reporttime: "04-09-2016 0:00", msisdn: "9987579170", city: "NOIDA", product: "Advantage3000", ceiindex: "85"…}

I want to convert above data into json format, e.g.:

  [[
    ['reporttime', "04-09-2016 0:00"],['msisdn', "9987579170"], ['city', 'NOIDA'], 
    ['product', 'Advantage3000']
  ]]

I am trying to create charts using jqplot. also getting ERROR: no data specified.

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
Laxmikant sahu
  • 73
  • 1
  • 14
  • Your sample "json format" is not valid JSON, though in any case I imagine what you actually want is an object (an array of arrays), not JSON. The conversion would be easy with `Object.keys()` and `.map()`, except note that the order of an object's keys is not guaranteed. – nnnnnn Oct 25 '16 at 06:03

2 Answers2

1

You need to have mapper function that converts input to output something like this.

Updated to have only selected fields in the output.

var input = {
  reporttime: "04-09-2016 0:00",
  msisdn: "9987579170",
  city: "NOIDA",
  product: "Advantage3000",
  ceiindex: "85",
  product: 'Advantage3000'
};

function mapper(input, requiredKeys) {
  var output = Object.keys(input).map(function(key) {
    if (input.hasOwnProperty(key) && requiredKeys.includes(key)) {
      return [key, input[key]];
    }
  }).filter(function(value) {
    return value !== undefined;
  });

  console.log(output);
}
var requiredKeys = ["city", "product", "reporttime"];
mapper(input, requiredKeys);
Sreekanth
  • 3,110
  • 10
  • 22
  • I know I suggested this above, but note that the OP's sample output doesn't include all of the input properties. (Not sure if they did that on purpose...) – nnnnnn Oct 25 '16 at 06:22
  • I modified the method to take the selected fields – Sreekanth Oct 25 '16 at 06:28
  • it this code will work for Object {reporttime: "04-09-2016 0:00", msisdn: "9986983200", city: "NOIDA", product: "Advantage3000", ceiindex: "56"…} – Laxmikant sahu Oct 25 '16 at 07:40
  • If you mean "Object {reporttime: "04-09-2016 0:00", msisdn: "9986983200", city: "NOIDA", product: "Advantage3000", ceiindex: "56"…}", it isn't understood in javascript natively as it is not a valid format. However, omitting "Object " from the string, it could be a valid JSON. So, you need to convert the given string to valid JSON by yourself. Hope this clarifies. – Sreekanth Oct 25 '16 at 15:41
-1
var responseArr = [];
for (var x in DataObj) {
  var initArr = [];
  initArr.push(x);
  initArr.push(DataObj[x]);
  responseArr.push(initArr);
};

the output of this you can push to another array to get int the format you want. Pass you input object to the for loop.

Shubham Gautam
  • 329
  • 3
  • 7