0

I like to convert this txt to json file like the format I attached.

here my txt: `

WarehouseId WarehouseName   SKU NUMBER  SKU Name    rackSection gatewayID   tagAddress  lightActive caseCount
50  Lakewood    45234   Mountain Dew (20oz) 4   1   1   True    24
50  Lakewood    65197   Dr Pepper (20oz)    5   1   2   True    24
50  Lakewood    45206   Diet Dr Pepper (20oz)   5   1   3   True    24
50  Lakewood    65209   Diet Pepsi (20oz)   6   1   4   True    24

I tried to use data.split(" ") but after that Idk what is the next step and how to make it to json file.

this is the result I like to achieve ( a json file ) :

[
    {
        "warehouseId" : 50,
        "WarehouseName":"Lakewood",
        "SKU NUMBER":45234,
        "SKU Name":"Mountain Dew (20oz)",
        "rackSection":4,
        "gatewayID":1,
        "tagAddress":1,
        "lightActive":"True",
        "caseCount":24
    },
    {
        "warehouseId" : 50,
        "WarehouseName":"Lakewood",
        "SKU NUMBER":65197,
        "SKU Name":"Dr Pepper (20oz)",
        "rackSection":5,
        "gatewayID":1,
        "tagAddress":2,
        "lightActive":"True",
        "caseCount":24
    },
    {
        "warehouseId" : 50,
        "WarehouseName":"Lakewood",
        "SKU NUMBER":45206,
        "SKU Name":"Diet Dr Pepper (20oz)",
        "rackSection":5,
        "gatewayID":1,
        "tagAddress":3,
        "lightActive":"True",
        "caseCount":24
    },
    {
        "warehouseId" : 50,
        "WarehouseName":"Lakewood",
        "SKU NUMBER":65209,
        "SKU Name":"Diet Pepsi (20oz)",
        "rackSection":6,
        "gatewayID":1,
        "tagAddress":4,
        "lightActive":"True",
        "caseCount":24
    }
]```


Many thanks.
Mahmood
  • 13
  • 2
  • Are you happy with the results of your `split` operation? If so, then maybe we should continue the problem solving process from there. I'm worried already though, because you are splitting on 4 spaces, but there appear to be only 2 spaces between `50` and `Lakewoord` in your example. If not, then Maybe you have **tabs** in the original and should be splitting on tabs? – Wyck Jan 22 '23 at 16:49
  • I believe its not space , I believe its \t. for some reason its showing like spaces but they are not spaces ! thanks for helping me all. I love stackoverflow, wishing one day I have more knowledge like you guys to help people. – Mahmood Jan 22 '23 at 17:27

1 Answers1

0

This question will probably be closed as a duplicate, but here is a simple solution:

const lines = file.split('\n');
const headers = lines[0].split('\t');

let data = [];

for(let i = 1; i < lines.length; i++) {
  const line = lines[i].split('\t');
  
  const obj = {};
  for(let j = 0; j < headers.length; j++) {
    obj[headers[j]] = line[j];
  }
  
  data.push(obj);
}
Oliver
  • 1,465
  • 4
  • 17