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);
Related
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);
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);
}
}
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
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.
I'm trying to load a json file from a URL and parse it within Dart. So I had tried the following code as suggested from some links when I google for it:
HttpRequest.getString("hellknight2.js").then((response)
{
var model = new JSON.parse(response);
});
However, it seems to not work anymore on Dart SDK version 0.4.3.5_r20602. What is the current best way to get a Json file mapped to an object in Dart?
Simply use json of the dart:convert package. Here is an example :
import 'dart:convert';
main() {
final myJsonAsString = '{"a": 1, "b": "c"}';
final decoded = json.decode(myJsonAsString);
....
}
See Parsing JSON for more details.
in my case
JSON.decode
didn't work.
Instead I had to use :
import 'dart:convert' as JSON;
final json=JSON.jsonDecode(myJsonAsString);
Here is my solution :) At first, you need to import the convert package:
import 'dart:convert';
var res = json.decode(response.body);
then you can get values by key, like below:
print(res["message"]);
It depends on a lot of things.
Is the json text you get is an array or a map?
You can try with:
Map model = new parse(response);
Or
List model = new parse(response);
but you need to import JSONObject by Chris Buckett into your package
import "package:json_object/json_object.dart";
You can install it from pubspec adding this dependency
json_object
There's a new pub package for this:
Victor Savkin - Serializers.
I didn't use it but seems to me that it will suite you. Try it out
you can try this package. pub: g_json
dynamic model = JSON.parse(JsonStringFromAnywhere);
final name = model['name'].stringValue;
// OR
final name = model.name;