angular import json file - json

i try to dynamic import json files from assets folder.
static it work's fine:
import * as data from '../assets/data/fr_fr.json';
but it throw's an error if i try to do it dynamicaly:
error Message: Error: Uncaught (in promise): Error: Cannot find module '../assets/data/fr_fr.json'.
import(path).then(res => console.log({res});
hint: i use es2020, angular 14.

Related

svelte - reading json file from local folder

My svelte app is required to read json file from the public folder.
I followed exactly the rollup setup from this link, then add json to my app.svelte:
import * as port from '/port.json';
port.json is located at the public folder together with index.html.
But I keep getting this error:
main.js:11 Uncaught ReferenceError: port is not defined at main.js:11
and I am getting this message from Terminal which I am not sure what it means:
(!) Missing global variable name Use output.globals to specify browser
global variable names corresponding to external modules /port.json
(guessing 'port')
How can I resolve this?
You have two options.
Move the file to your src/ folder and bundle it with the rest of your application code using Rollup. This is where you need #rollup/plugin-json to bundle json files. You can then import it like so:
<script>
import json from './port.json';
</script>
<p>{JSON.stringify(json)}</p>
Keep the file in your public/ folder and retrieve it at runtime using fetch.
<script>
let fetchJson = fetch('port.json').then(res => res.json());
</script>
{#await fetchJson}
<p>Loading JSON</p>
{:then result}
<p>{JSON.stringify(result)}</p>
{/await}
Export the object and rename the file from .json to .json.js.
port.json.js
export let myJson = {
name: "hello world"
}
Component:
<script>
import json from './port.json';
</script>
<p>{JSON.stringify(json)}</p>

deno import JSON file as module

I have a simple file that imports a json:
main.ts
import json from './file.json'
However, deno throws the following error when importing a json file:
$ deno run main.ts
Compile file:///home/path/to/project/main.ts
error: Uncaught TypeError: Cannot resolve extension for "file:///home/path/file.json" with mediaType "Json".
at getExtension ($deno$/compiler.ts:218:13)
at new SourceFile ($deno$/compiler.ts:263:22)
at Function.addToCache ($deno$/compiler.ts:339:16)
at processImports ($deno$/compiler.ts:743:31)
at async processImports ($deno$/compiler.ts:753:7)
at async compile ($deno$/compiler.ts:1316:31)
at async tsCompilerOnMessage ($deno$/compiler.ts:1548:22)
at async workerMessageRecvCallback ($deno$/runtime_worker.ts:74:9)
The file path is correct and the file is a valid JSON. The Typescript compiler should allow this by default.
I also tried to explicitly enable resolveJsonModule:
tsconfig.json
{
"compilerOptions": {
"resolveJsonModule": true
},
"include": [
"**/*"
]
}
and run it with the config but still get the same error:
$ deno run main.ts --config=tsconfig.json
Compile file:///home/path/to/project/main.ts
error: Uncaught TypeError: Cannot resolve extension for "file:///home/path/file.json" with mediaType "Json".
at getExtension ($deno$/compiler.ts:218:13)
at new SourceFile ($deno$/compiler.ts:263:22)
at Function.addToCache ($deno$/compiler.ts:339:16)
at processImports ($deno$/compiler.ts:743:31)
at async processImports ($deno$/compiler.ts:753:7)
at async compile ($deno$/compiler.ts:1316:31)
at async tsCompilerOnMessage ($deno$/compiler.ts:1548:22)
at async workerMessageRecvCallback ($deno$/runtime_worker.ts:74:9)
What's wrong here?
As per the following thread support for reading json files was removed just before shipping deno 1.0
https://github.com/denoland/deno/issues/5633
However, you can use the following syntax for reading a json file
Deno.readTextFile('./file.json').then(data => {
console.log(JSON.parse(data))
})
or
const data = JSON.parse(Deno.readTextFileSync('./file.json'));
Also, be sure to run the file containing above code with --allow-read flag. Otherwise you will ge a permission denied error
deno run --allow-read index.ts
Since Deno 1.17 JSON can now once again be imported in ESM. Import assertions must now be used:
import data from "./file.json" assert { type: "json" };
console.log(data);
For more info, see https://examples.deno.land/importing-json.
As an alternative to Afeef's answer, since a JSON file is a valid object literal, you can add export default to it and change the extension to .js.
from settings.json
{
"something": {
"foo": "bar"
}
}
to settings.js
export default {
"something": {
"foo": "bar"
}
}
And now you can can use import
import settings from './settings.js'
console.log(typeof settings) // object
constole.log(settings.something.foo) // bar
The upside, aside from being shorter, is that you don't need --allow-read access

Import a local json file with Angular

I have a simple .json file outside of my project. Like this :
| common
| configuration.json
| angular-app
| src
| app
| my-component
| my-component.component.ts
| angular.json
In my-component.component.ts, i want to import configuration.json. I tried import configuration from '../../../../common.configuration.json' but Angular just keep throwing this error :
ERROR in src/app/record/record.component.ts(4,23): error TS2732: Cannot find module '../../../../common/configuration.json'. Consider using '--resolveJsonModule' to import module with '.json' extension
And when i try ng serve --resolveJsonModule, i got this error : Unknown option: '--resolveJsonModule'
I can't move configuration.json. The common directory is shared with other projects.
How do you import a local json file in an Angular project ?
If you're using typescript 2.9+ (Angular 6.1+), you can import JSON modules so it will get compiled into the application. Older version don't support this so that may be your issue.
All you need to do is make sure the following three compiler options are enabled in your tsconfig.json:
{
...
"compilerOptions": {
"resolveJsonModule": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true
...
}
}
Then you can import JSON modules in any TS file:
import jsonContents from '../../contents.json';
I'm not exactly sure what you mean but I guess you want to use the config values in your component, right?
According to this tutorial this can be fixed by creating a type definition file json-typings.d.ts in your app root folder with the following contents:
declare module "*.json" {
const value: any;
export default value;
}
Try by using http call:
this.http.get(`yourpath/..../common/configuration.json`).subscribe((resp: any) => {
console.log(resp)
});

How to parse external JSON file in the .jsx file

I'm new with React and need some one with my json file Parsing problem. I am having a PerfCompare.jsx with a variable needed in the following compare. And i need this var parsing from a external JSON file(trscConfig.JSON). I am using this lines to do. but always get this SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
trscConfig.JSON
{
"server" : "http://myserver.com"
}
PerfCompare.jsx
import React, { Component } from 'react';
import { Form, Input, Button, Radio, Row, Table, Divider, Progress, Alert } from 'antd';
import math from 'mathjs';
import { stringify } from 'qs';
import PerffarmRunJSON from './lib/PerffarmRunJSON';
import JenkinsRunJSON from './lib/JenkinsRunJSON';
import benchmarkVariantsInfo from './lib/benchmarkVariantsInfo';
import './PerfCompare.css';
//import App_DATA from './trscConfig.JSON';
const server_2 = JSON.parse('./trscConfig.JSON').server;
Use fetch():
const response = await fetch('trscConfig.JSON');
const json = await response.json();
const server_2 = json.server;
Or, if your build tool doesn't support await yet:
fetch('trscConfig.JSON')
.then(response => response.json())
.then(json => {
const server_2 = json.server;
});
In either case, downloading the JSON file at runtime will mean the response will not be available immediately. If this is a React component, I suggest doing this in componentDidMount().
Alternatively, if the JSON file is a static asset:
import {server as server_2} from './trscConfig.JSON';
JSON.parse doesn't know how to make HTTP requests/read files - it just parses exactly what you've passed in. In this case, it's failing because it's trying to convert the literal string ./trscConfig.JSON into a JSON object!
There's two ways you could get this working:
Load in the JSON via your module bundler, as you're doing in the commented out line in your code. I believe Webpack (and most others) support this out of the box, but your configuration might have it disabled, intentionally or otherwise. It might also be because you're using uppercase file extensions - try it with a file that has .json in lowercase.
Use XMLHttpRequest, the Fetch API, or a third-party HTTP client library to download the JSON at runtime, and then parse the downloaded text.

How i can use a function in sikuli which is defined in an another sikuliscript?

I try to use Sikuli. I will have 2 Files. One of them will be the "main" file and one of then is for functions.
The main-file I have called "test" and the file for the Function I have called "importi".
If I run the main file, I will get the error:
[error] Fehlermeldung: Traceback (most recent call last): File
"C:...\Temp\sikuli-tmp8331266965127754273.py",line 3, in
importi.help()
AttributeError: 'module'object has no attribute 'hallo'
This is my Code of the main-file:
import importi
importi.hallo()
and this is the code of the File with the function:
anzeige = "Hallo"
def help():
popup(anzeige)
I think in the calling function you should write -
import importi
importi.help()
in above code "help" is the function name defined in called (or imported) function.
At the same time, below code should be saved as importi.sikuli file.
anzeige ="Hallo"
def help():
popup(anzeige)
So, to summarize.
File importi.sikuli has -
anzeige ="Hallo"
def help():
popup(anzeige)
And calling function (whatever name it has) is -
import importi
importi.help()