kogyikyaw kogyikyaw - 4 months ago 16
JSON Question

Read the raw data from text file and then convert them into expected json format with jquery

1.Read the raw data from data.txt

this is the sample data from text file

nike sport shirt 85 20<br>
nike sneeker 120 15<br>
nike pants 90 20<br>
spring field short 50 40<br>
spring field dress 78 50<br>
spring field bags 48 10<br>
adidas boost shoes 65 10<br>
adidas trainer 48 10<br>
adidas jacket 140 35<br>
H&M sweaters 49 15<br>
H&M swimwear 88 30<br>
H&M modern classics 200 5<br>


2.Convert them into expected
json
format


/* expected json format */
{
'nike': [
{ catagory: 'sport shirt', price: 85, quantity: 20 },
{ catagory: 'sneeker', price: 120, quantity: 15 },
{ catagory: 'pants', price: 90, quantity: 20 }
],
'spring field': [
{ catagory: 'short', price: 50, quantity: 40 },
{ catagory: 'dress', price: 78, quantity: 50 },
{ catagory: 'bag', price: 48, quantity: 10 }
],
'adidas': [
{ catagory: 'boost shoes', price: 65, quantity: 10 },
{ catagory: 'trainer', price: 48, quantity: 20 },
{ catagory: 'jacket', price: 140, quantity: 35 }
],
'H&M':[
{ catagory: 'sweaters', price: 49, quantity: 15 },
{ catagory: 'swimwear', price: 88, quantity: 30 },
{ catagory: 'modern classics', price: 200, quantity: 5 }
]
}


So,how to read the raw data from text file and then convert them into expected json format with jquery?

Thanks

Answer

You can use XMLHttpRequest(), for loop, .shift(), Object.hasOwnProperty(), .split(), .trim(), .forEach()

var obj = {};
var items = ["category", "price", "quantity"];
var fn = function(curr, tmp, obj, item, items) {
  curr.forEach(function(el, index) {
    tmp[items[index]] = el;
  })
  obj[item].push(tmp)
}
var request = new XMLHttpRequest();
request.open("GET", "data.txt", true);
request.onload = function() {
  var arr = this.responseText.split(/<br>/);
  for (var i = 0; i < arr.length; i++) {
    var curr = arr[i].trim().split(/\s+/);
    var item = curr.shift();
    var tmp = {};
    if (item) {
      if (!obj.hasOwnProperty(item)) {
        obj[item] = [];
      }
      fn(curr, tmp, obj, item, items)
    }
  }
  console.log(obj)
}
request.send();

plnkr http://plnkr.co/edit/xAYaoll9FVjEUqSXaslT?p=preview