Reading decimal values from JSON - json

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)?

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);

Related

How to read CSV file from device storage in flutter

I want to import data into firebase database from a CSV file in flutter. So I pick .CSV file from device using file picker. Now how can I read data from that file?
At first import file_picker and CSV package from dart packages. Than define the method pickFile() as i have given below. it will pick the file from device storage and after selection it will print data. pickFile() funtion shoulb be called to get result.
import 'package:file_picker/file_picker.dart';
import 'package:csv/csv.dart';
import 'dart:convert' show utf8;
pickFile() async {
FilePickerResult result = await FilePicker.platform.pickFiles();
if (result != null) {
PlatformFile file = result.files.first;
final input = new File(file.path).openRead();
final fields = await input
.transform(utf8.decoder)
.transform(new CsvToListConverter())
.toList();
print(fields);
}
}

Making json files in Scala

I am working on a Scala app. I have a method that gives me JSON and I convert it to string using toString as follows:
def myjson(fileName:String){
val myJson = myData.getJsonData().toString
}
Here getJsonData() will give me a .json. I want to write this .json into a file and save this .json in resources section in my project. Format of the file should be ".json". Name of the file is the one which I am getting in above method. How can I do that?
One approach would be as follow
import java.nio.file.{Paths, Files}
import java.nio.charset.StandardCharsets
def myjson(fileName:String){
val myJson = myData.getJsonData().toString
val path = s"/user/myProject/..../resources/$fileName"
Files.write(Paths.get(path), myJson.getBytes(StandardCharsets.UTF_8))
}
I understand that fileName: String will be something like filename.json

How to read local json import in flutter?

I have a JSON file in the flutter directory, not in assets.
json_data.json:-
{
"foo" : "bar"
}
I want to read this JSON on different files.
like
myfile.dart:-
import "package:mypackage/json_data.json" as data;
import 'dart:convert';
var my_data = json.decode(data);
I am getting the error:-
The name 'data' refers to an import prefix, so it must be followed by '.'.
Try correcting the name to refer to something other than a prefix, or renaming the prefix.
What is the problem here? why can't I read JSON from local import in flutter?
You should look into loading assets in flutter. You can't simply import an arbitrary file. Importing is for source code/libraries.
You need to declare this file as an asset in your pubspec.yaml
flutter:
assets:
- json_data.json
Then in your code you can load this asset as a String:
import 'package:flutter/services.dart' show rootBundle;
Future<String> getJson() {
return rootBundle.loadString('json_data.json');
}
You can decode the JSON with your existing code, but it should be placed in a method body somewhere. You call this getJson function to retrieve the JSON String:
var my_data = json.decode(await getJson());
Alternatively, you could simplify this even further by putting the contents of your JSON file directly into the code as a String, but this may not be possible, it depends on your intended use of this JSON.
const String data = '''
{
"foo" : "bar"
}
''';
var my_data = json.decode(data);

How do I save the data in a local JSON file as a variable in node?

The code above works however I would like to load the searchStrings array from a JSON file.
My goal is to have the json file on a shared drive so my coworkers are able to edit the names.
You can use following:
var someObject = require('./somefile.json')
JSON can be imported via require just like Node modules. (See Ben Nadel's explanation.)
You would generally want to store it as a global variable, rather than re-loading it on every keyup event. So if the JSON is saved as watchlist.json, you could add
var watchlist = require('./watchlist');
at the top of your code. Then the search command could be written (without needing the for loop) as:
kitten = kitten.toLowerCase();
if (watchlist.entities.indexOf(kitten) !== -1) {
alert('potential watchlist');
}
In the latest versions of Node you can simply use imports!
CommonJs:
const jsonContent = require('path/to/json/file.json')
ES6:
import jsonContent from 'path/to/json/file.json'
You can also import JSon files dinamically, take the following example:
if (condition) {
const jsonContent = require('path/to/json/file.json')
// Use JSon content as you prefer!
}
that way, you only load your JSon file if you really need it and your code will score better performances!
Do you prefer an old school approach?
ES6:
import fs from 'fs' // or const fs = require('fs') in CommonJs
const JSonFile = fs.readFileSync('path/to/json/file.json', 'utf8')
const toObject = JSON.parse(JSonFile)
// read properties from `toObject` constant!
Hope it helps :)

Static typing with JSON and TypeScript

Say I have this JSON file:
{
"foo": 1,
"bar": true,
"baz": "yes"
}
is there a way to import that file and get static typing with TypeScript?
with plain Node.js, we do:
const json = require('./file.json');
but with TS, is there a way to do:
import json = require('./file.json');
is there not a way to get static typing like this? It should be easy, right?
IMO, you should just be able to do
typeof 'path/to/json/file.json'
so that would be:
export type MyInterface = typeof 'path/to/json/file.json'
and that will give you a type.
You can essentially do the same as standard Node.js but use an interface and attach it to the variable you're require-ing into.
interface File {
foo: number
bar: boolean
baz: string
}
const jsonFile: File = require('./file.json')
If the data read and parsed from the file doesn't conform to the interface, TS should throw an error.
There is no current method of dynamically analyzing an unread JSON file to acquire a type for it.