简体   繁体   English

解析来自 API 的文本并转换为对象

[英]Parsing text from API and converting to object

I'm reading data from a text file which looks something like this:我正在从一个看起来像这样的文本文件中读取数据:

#start
#p 09060 20131010
#p 09180 AK
#p 01001 19110212982
#end
#start
#p 09060 20131110
#p 09180 AB
#p 01001 12110212982
#end

Parsing it to an object:将其解析为一个对象:

var result = data.match(/#start[\s\S]+?#end/ig).map(function(v){

    var lines = v.split('\n'),
        ret = {};

    $.each(lines, function(_, v2){
        var split = v2.split(' ');
        if(split[1] && split[2]) 
            ret[split[1]] = split[2];
    });

    return ret;
});

This would give me a list of objects which looks something like:这会给我一个看起来像这样的对象列表:

[{ 09060: 20131010, 09180: 'AK' }, { 09060: 20131110, 09180: 'AB' }] //etc...

However, I've noticed that each entry contains duplicates, which would cause my method to overwrite the properties:但是,我注意到每个条目都包含重复项,这会导致我的方法覆盖属性:

#start
#p 09060 20131110
#p 09180 AB
#p 01001 12110212982
#p 20000
#p 20001 ABC
#p 20002 123
#p 29999
#p 20000
#p 20001 CDE
#p 20002 345
#p 29999
#end

I would like to hear your ideas how to handle this.我想听听你的想法如何处理这个问题。 My first thought is to identify "chunks" and create lists when they appear, and create a property like:我的第一个想法是识别“块”并在它们出现时创建列表,并创建一个属性,如:

{ 
    09060: 20131010, 
    09180: 'AK',
    20000_29999: [
        { 20001: 'ABC', 20002: 123 }, { 20001: 'CDE', 20002: 456 }
    ]
}

I'm not sure how do identify the "chunks" in the loop, without specifying the keys ( 20000 and 29999 in this case).我不确定如何识别循环中的“块”,而不指定键(在这种情况下为2000029999 )。

Do you guys have any suggestions?大家有什么建议吗?

Use an array to hold the values.使用数组来保存值。

var result = data.match(/#start[\s\S]+?#end/ig).map(function(v){

    var lines = v.split('\n'),
        ret = {};

    $.each(lines, function(_, v2){
        var split = v2.split(' ');
        if(split[1] && split[2]) {
           // use array to hold values
           ret[split[1]] ||= [];
           ret[split[1]].push(split[2]);
        }      
    });

    return ret;
});

I wonder how will you use this object, you can use the following structures:我想知道你将如何使用这个对象,你可以使用以下结构:

[
  {
    "20001": [
      "ABC",
      "CDE"
    ],
    "09060": "20131110"
  },
  {
    "20001": [
      "ABC",
      "CDE"
    ],
    "09060": "20131110"
  }
]

OR或者

[
  {
    "20001": {
      "ABC": 1,
      "CDE": 1
    },
    "09060": "20131110"
  },
  {
    "20001": {
      "ABC": 1,
      "CDE": 1
    },
    "09060": "20131110"
  }
]

OR或者

[
  [
    [
      "20001",
      "ABC"
    ],
    [
      "20001",
      "CDE"
    ],
    [
      "09060",
      "20131110"
    ]
  ],
  [
    [
      "20001",
      "ABC"
    ],
    [
      "20001",
      "CDE"
    ],
    [
      "09060",
      "20131110"
    ]
  ]
]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM