1

I'm trying to read a JSON file in my Angular project. The file is located in the assets folder. The file has decimal values like:

{
  "valueA": 0.40000000000002,
  "valueB": 23.99999999999999995
}

My problem is that the values I got from importing the file are rounded to:

{
  "ValueA": 0.4
  "ValueB": 25
}

Is there a way to load the JSON with the exact digits from the source? Or convert them to a string? Unfortunately I have no way to change the source to split the numbers at the dot or to save them as a string. I could edit it in the pipeline that seeds the data but to me that looks like a really messy solution.

Currently I import and use the JSON like this:

import MyJson from 'src/assets/MyJson.json'

export class MyService {
  private myJson = Object.assign(MyJson);

  public getFieldsIWant() {
    return this.myJson.theFields.iWant;
  }
}

The main problem, I think, is with the first line import {.... If I print the imported File, it already "converted" the decimal place. Is there any other way to import JSON Files in TS so that this doesn't happen (already tried the import via the httpClient, same result)?

KastenBrot
  • 87
  • 2
  • 13

1 Answers1

1

You can use libraries like https://github.com/josdejong/lossless-json to replace JSON.parse

const fs = require('fs');
const LosslessJSON = require('lossless-json');

const fileContents = fs.readFileSync('./data.json', 'utf8');

let json = LosslessJSON.parse(fileContents);

jogerj
  • 128
  • 8
  • I thought of an other library to parse the JSON to. But the main problem is with the import of the file (just updated the question). But thanks for the answer! – KastenBrot Jul 19 '22 at 12:06
  • I've updated my answer to provide an alternative method of reading the json file. It would read the file without parsing it, so then you can parse it with the library – jogerj Jul 19 '22 at 12:28
  • As of this answer https://stackoverflow.com/questions/43048113/use-fs-in-typescript, fs is not supported by Typescript. Which makes sense. I cant access files on the servers filesystem from the client-side in runtime. The only solution I can think of is to modify the JSON before loading it into the app. – KastenBrot Jul 21 '22 at 08:07