从文本文件中读取原始数据,然后使用jquery将它们转换为预期的json格式

时间:2016-08-01 06:14:23

标签: jquery json

1.从data.txt中读取原始数据
这是来自文本文件的示例数据

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.将它们转换为预期的json格式

/* 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 }
    ]   
}

那么,如何从文本文件中读取原始数据,然后使用jquery将它们转换为预期的json格式?

由于

1 个答案:

答案 0 :(得分:0)

您可以使用XMLHttpRequest()for循环,.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