- Ошибка компилятора Typescript при импорте файла json
- 6 ответов
- Why can’t Python parse this JSON data?
- 9 Answers 9
- Как я могу решить «org.json.simple.JSONObject не может быть решен»?
- 6 ответов
- JSON импорт не работает, но из того же источника сервера
- 2 ответа
- Loading JSON file with ES6 import to browser #239
- Comments
- stat92 commented Aug 7, 2018
- catamphetamine commented Aug 7, 2018
- catamphetamine commented Aug 8, 2018
- RoXuS commented Apr 3, 2019 •
- catamphetamine commented Apr 3, 2019
- RoXuS commented Apr 3, 2019
- brianreeve commented May 16, 2019
- catamphetamine commented May 16, 2019
- catamphetamine commented May 16, 2019
- catamphetamine commented May 17, 2019 •
- catamphetamine commented May 17, 2019 •
- catamphetamine commented May 17, 2019
- brianreeve commented May 17, 2019 •
- catamphetamine commented May 17, 2019
- brianreeve commented May 17, 2019
Ошибка компилятора Typescript при импорте файла json
таким образом, код прост:
сгенерированный javascript является правильным и при запуске сервера JS узла, журнал консоли json.Сервер печатает «
компилятор typescript (commonjs), однако, как-то не особенно нравится эта ситуация и бросает: «не удается найти модуль»../ статические / звонки.формат JSON'».
конечно, я попытался написать .д.ТС файл, например:
это, очевидно, бросает: «объявление окружающего модуля не может указать относительное имя модуля».
Я также пробовал разные варианты, например:
а потом требует:
не работает должным образом и имеют свои собственные небольшие ошибки компилятора 🙂
Я хочу использовать внешний .JSON-файл, потому что я использую commonjs serverside и AMD clientside, и мне нужен один файл для загрузки констант.
6 ответов
использовать var вместо import .
вы загружаете файл JSON, а не модуль, так import не следует использовать в этом случае. Когда var используется require() снова рассматривается как нормальная функция.
если вы используете узел.JS определение, все должно просто работать, иначе require необходимо будет определить.
другое решение-изменить data.json to data.ts и экспортировать вот так
и импорт, как и следовало ожидать:
это может и сделать с помощью import заявление при использовании webpack v2 который уже упакован с в JSON-погрузчик.
обратите внимание, что это не асинхронный
и typings.d.ts файл добавить следующий модуль подстановки чтобы избежать ошибки typescript, говоря: Cannot find module
для всех, кто интересуется async импорт, Регистрация эта статья 2uality
в своем tsconfig.json или jsconfig.json . Теперь импортирует такие как:
должен быть разрешен и иметь правильные typings тоже!
по состоянию на машинопись 2.9 вы можете импортировать файл JSON изначально без каких-либо дополнительных взлома/загрузки.
следующий отрывок копируется из указанной выше ссылки.
. TypeScript теперь может импортировать файлы JSON в качестве входных файлов при использовании стратегии узла для moduleResolution. Это означает, что вы можете использовать файлы json как часть своего проекта, и они будут хорошо набрали!
Источник
Why can’t Python parse this JSON data?
I have this JSON in a file:
I wrote this script to print all of the JSON data:
This program raises an exception, though:
How can I parse the JSON and extract its values?
9 Answers 9
Your data is not valid JSON format. You have [] when you should have <> :
- [] are for JSON arrays, which are called list in Python
- <> are for JSON objects, which are called dict in Python
Here’s how your JSON file should look:
Then you can use your code:
With data, you can now also find values like so:
Try those out and see if it starts to make sense.
Your data.json should look like this:
Your code should be:
Note that this only works in Python 2.6 and up, as it depends upon the with -statement. In Python 2.5 use from __future__ import with_statement , in Python
Justin Peel’s answer is really helpful, but if you are using Python 3 reading JSON should be done like this:
Note: use json.loads instead of json.load . In Python 3, json.loads takes a string parameter. json.load takes a file-like object parameter. data_file.read() returns a string object.
To be honest, I don’t think it’s a problem to load all json data into memory in most cases. I see this in JS, Java, Kotlin, cpp, rust almost every language I use. Consider memory issue like a joke to me 🙂
On the other hand, I don’t think you can parse json without reading all of it.
«Ultra JSON» or simply «ujson» can handle having [] in your JSON file input. If you’re reading a JSON input file into your program as a list of JSON elements; such as, [<[<>]>, <>, [], etc. ] ujson can handle any arbitrary order of lists of dictionaries, dictionaries of lists.
You can find ujson in the Python package index and the API is almost identical to Python’s built-in json library.
ujson is also much faster if you’re loading larger JSON files. You can see the performance details in comparison to other Python JSON libraries in the same link provided.
If you’re using Python3, you can try changing your ( connection.json file) JSON to:
Then using the following code:
There are two types in this parsing.
- Parsing data from a file from a system path
- Parsing JSON from remote URL.
From a file, you can use the following
This arcticle explains the full parsing and getting values using two scenarios.Parsing JSON using Python
Here you go with modified data.json file:
You can call or print data on console by using below lines:
Expected output for print(data_item[‘parameters’][0][‘id’]) :
Expected output for print(data_item[‘parameters’][0][‘id’]) :
As a python3 user,
The difference between load and loads methods is important especially when you read json data from file.
As stated in the docs:
json.load:
Deserialize fp (a .read()-supporting text file or binary file containing a JSON document) to a Python object using this conversion table.
json.loads:
json.loads: Deserialize s (a str, bytes or bytearray instance containing a JSON document) to a Python object using this conversion table.
json.load method can directly read opened json document since it is able to read binary file.
As a result, your json data available as in a format specified according to this conversion table:
Источник
Как я могу решить «org.json.simple.JSONObject не может быть решен»?
Когда я пытаюсь открыть свой JSP через Tomcat, я получаю следующие сообщения:
Тип org.json.simple.JSONObject не может быть разрешен. На него косвенно ссылаются необходимые файлы .class.
Метод getJSONObject () из типа Ejercicio ссылается на отсутствующий тип JSONObject.
У меня есть класс Java, который выглядит так:
Мой JSP выглядит следующим образом:
Я добавил много jar-файлов как в папку lib внутри WEB-INF, так и в библиотеку Tomcat, пытаясь решить проблему без результатов (commons-beanutils-1.8.1, commons-collection-3.2.1, commons-lang-2.5 , commons-logging-1.1.1, ezmorph-1.0.6, java-json, javax.json-1.0, json-lib-2.4-jdk15, json-rpc-1.0, json-simple-1.1.1-sources, org .json ) .
Когда я скомпилировал класс java, я получил сообщение «Некоторые входные файлы используют непроверенные или небезопасные операции». Может ли это быть связано с не компиляцией jps?
6 ответов
Во-первых, вам не нужен json-simple.jar в вашем проекте.
Поэтому удалите import org.json.simple.*
Во-вторых, лучше всего импортировать из вашего фляги только необходимые классы. Поэтому вы можете заменить import org.json.*; на
Вы можете скачать необходимый jar, для меня то, что сработало, это загрузить мой отсутствующий json 20140107 jar и добавить операторы импорта, как показано ниже:
import org.json.JSONException;
import org.json.simple.JSONObject;
Для меня, безусловно, скачать банку и добавить ее в простое затмение
Просто следуйте этим шагам 1. Загрузите файл .jar по этой ссылке https://jar-download.com/artifacts/. org.json 2. найдите и распакуйте файл json.jar
В eclipse — щелкните правой кнопкой мыши по вашему проекту и перейдите к пути сборки -add external jar -hit apply
Это it; надеюсь это поможет ребятам
Это работает для пакета org.json:
Скопируйте исходные файлы отсюда
Примечание. Это ссылка на исходный код (JSON-java), взятая из http://www.json.org/
В папку \ src \ org \ json
В Eclipse нажмите кнопку Открыть перспективу, затем Ресурс.
Щелкните правой кнопкой мыши файл org.json и нажмите «Обновить», чтобы добавить исходный код Java в проект.
Я нигде не нашел правильного ответа, но моя проблема с библиотекой TomCat JSON была связана с развертыванием артефакта. Если вы используете intelliJ, перейдите к структуре проекта >> артефакты и добавьте jar в папку lib
Источник
JSON импорт не работает, но из того же источника сервера
Я изучаю синхронный импорт JSON Ajax в мой код JavaScript.
Ссылка на источник JSON, которую я хочу использовать:
Но чтобы не загружать сервер, неделю назад или около того я создал статическую страницу, показывающую те же данные в
Мой импорт JavaScript, как показано ниже:
Оттуда я получаю нужные мне значения в jsonData, например, (x, y) координаты как
Он прекрасно работает со ссылкой noobjson.php, но когда я указываю на default.php, ничего не появляется. Загрузка страницы заняла какое-то время, что выглядело как загрузка значений json, но alert(«Galaksi value retrieved») возвращает undefined .
Я скопировал и вставил вывод со страницы default.php в средство проверки JSON в Интернете, и он показал ОК. Я не знаю, почему статическая ссылка работает, а ссылка на основе $_GET — нет.
Может кто-нибудь подсказать мне, что происходит?
Я всегда получаю Не удалось загрузить информацию, если не использую URL-адрес noobjson.
Как будто этот URL с GET не существует.
2 ответа
В default.php я сделал следующее:
Поэтому я заменил все отдельные эхо-сигналы на $ JSONstr, как показано ниже.
Затем я добавил echo $ JSONstr; в конце. Первоначально я сделал это, чтобы я мог сделать:
Но это создает <\ "Galaksi \": 1>на выходе JSON вместо предполагаемого
Поэтому я удалил json_encode и просто вывел строку. Также я должен был удалить
На этот раз я также использовал другой тестер JSON.
Первоначально я использовал http://www.freeformatter.com/json-validator.html, который говорит JSON Действительный для моего начального вывода JSON. Затем я использовал этот, который сказал, что мой выходной URL JSON был недействительным, хотя если я скопировал + вставил выходную строку, он вернул верный. http://jsonformatter.curiousconcept.com/
Поэтому, после внесения этих изменений и удаления «
Источник
Loading JSON file with ES6 import to browser #239
Comments
stat92 commented Aug 7, 2018
We use ES6 import without any build step. ES6 import doesn’t load json files due to HTML spec. So I am getting next error when loading index.es6.js:
Failed to load module script: The server responded with a non-JavaScript MIME type of «application/json». Strict MIME type checking is enforced for module scripts per HTML spec.
The text was updated successfully, but these errors were encountered:
catamphetamine commented Aug 7, 2018
catamphetamine commented Aug 8, 2018
Seems that .js extension is also required, not just .json .
I won’t be changing all imports to .js extension.
RoXuS commented Apr 3, 2019 •
+1 on browser it doesn’t work due to import json.
catamphetamine commented Apr 3, 2019
Ok, I’m reopening this if people’re having issues with it.
But I won’t be changing .json to .js .
RoXuS commented Apr 3, 2019
Browser don’t support direct json import so you have to transform the json to an export in js file.
brianreeve commented May 16, 2019
+1 or ES6 imports of the lib won’t work natively in browsers. Your own README examples are failing in modern browsers. For example:
import < AsYouType >from ‘libphonenumber-js’
IMO your hard stance on this is fighting an unwinnable battle: «Strict MIME type checking is enforced for module scripts per HTML spec.» Solution proposed by OP is the way to go.
catamphetamine commented May 16, 2019
@brianreeve If your proposed solution is adding .js extensions to all imports then the answer is «No».
catamphetamine commented May 16, 2019
Actually, I would add .js extensions to all imports if the spec also supported importing .json .
If the spec doesn’t know how to import .json files then that’s a bad spec and it should be fixed.
To conclude, the .json files are left .json unless extremely required to be .js .
catamphetamine commented May 17, 2019 •
Well, you could test if the non-JSON version works first.
There’re several sub-packages and core is one of them.
You could somehow obtain metadata.json as a variable in the app and then import the core subpackage and pass metadata as the last argument.
If that works then we could work from there.
Otherwise post the error.
catamphetamine commented May 17, 2019 •
As a last resort, the library could ship .json.js files just for the inferior ES6 importing spec that could be used with the /custom subpackage.
catamphetamine commented May 17, 2019
So do the testing and I’ll do the rest.
brianreeve commented May 17, 2019 •
I’m very surprised at the resistance to using the platform and moving towards removing the dependency and complexity of build tools. I’m not attempting to engage in debate or argument. I was just adding to what others were saying above. As-is, this library is unusable on the modern web using import s natively.
Yes, webpack supports importing json directly through the json loader. However, it is not based on any approved standard. The first sentence of the MDN docs plainly says import «..is used to import features into JavaScript modules that have been exported by another module.» A JSON file is not a module. Additionally, under the covers, webpack’s json-loader converts a json file to a proper export.
Since ES6 modules are so widely supported now, I don’t plan to have any build step required for the web components I am developing.
As a quick test, I made a couple changes:
- Saved metadata.full.json as metadata.full.js and modified it to be:
- Updated index.js to change:
import metadata from ‘../metadata.full.json’
import metadata from ‘../metadata.full.js’
There are some downstream issues with loading the semver-compare dependency that I haven’t yet looked into, but the above seems to get past the bug with importing json metadata files.
Would it be acceptable to build js metadata files which export the metadata object, and change the imports to use the js file instead of the JSON?
catamphetamine commented May 17, 2019
I’m very surprised at the resistance to using the platform and moving towards removing the dependency and complexity of build tools.
I support the general initiative, not the actual implementation.
I’m not attempting to engage in debate or argument. I was just adding to what others were saying above.
Debating is fun and should be encouraged.
As-is, this library is unusable on the modern web using imports natively.
Yes, as-is it is unusable on the inferior «modern» import platform. When they fix their platform then we’ll talk.
Yes, webpack supports importing json directly through the json loader. However, it is not based on any approved standard.
JSON is an extremely convenient and standardized data format across the whole world and so it would make perfect sense for the spec authors to add the ability to import json .
Not doing so is oppressing the minority that favours json over js .
Isn’t Western civilization all about protecting the minorities of all kinds?
If yes, then we must fight for our right to keep json .
Since ES6 modules are so widely supported now, I don’t plan to have any build step required for the web components I am developing.
But you can still volunteer into testing, otherwise you’d be contradicting yourself being an evangelist of the platform.
There are some downstream issues with loading the semver-compare dependency that I haven’t yet looked into
Yeah, that’s the point: no one supports that new importing system of yours.
semver-compare could very easily be inlined though removing the dependency:
https://github.com/substack/semver-compare/blob/master/index.js
but the above seems to get past the bug with importing json metadata files.
So we don’t need to change all imports to .js then.
The only thing not supported by the import spec is the .json import then.
The conclusion follows that this library is able to get working with the import platform.
The workaround steps are:
- Import the /core subpackage instead of the root one.
- Pass metadata as the last argument to all functions of the /core subpackage.
metadata can be obtained by importing the .json.js files which can be generated from .json files by prepending export default to them. I could even see it being part of this library’s distribution package.
ES6 support JSON importing with the following syntax: import * as data from ‘./example.json’
Someone should test that.
brianreeve commented May 17, 2019
Debating is fun and should be encouraged.
Thanks for your additional comments. I just meant that I wasn’t trying to be contrary or difficult in my challenges to your replies.
JSON is an extremely convenient and standardized data format across the whole world and so it would make perfect sense for the spec authors to add the ability to import json.
Not doing so is oppressing the minority that favours json over js.
I can appreciate your sentiment, but don’t agree with your assessment that minority opinions are being oppressed if they don’t make it into a spec. I don’t even think that being a fan of json puts anyone in a minority (I definitely like it), but I imagine spec authors must consider A LOT of external and internal factors when determining what makes it in.
More to the point, as written, the import spec and implementation is clearly not intended for anything other than javascript modules. Calling it «inferior» to webpack’s json-loader approach is not constructive. I would argue webpack’s importing of json is a misuse of the feature.
Depending on the use case, there are alternative solutions that are fairly simple, such as loading JSON data via XHR, or exporting an object as we’ve seen.
If the spec allowed importing non-js files, like json, then why stop there? Why not allow importing text files like csv, yml, or binaries like images, videos, etc.? As you can see it would quickly spiral into deeper implications with security, memory management, caching, etc. since there are already appropriate mechanisms in place to manage those.
Yeah, that’s the point: no one supports that new importing system of yours.
This is a bold statement. It has been in the spec since ECMAScript 2015 and is now very widely supported across browsers. Libraries are definitely shipping with using import .
The fact is the platform technology has properly plugged the holes which were previously patched through tooling and process. Since authors of the tooling are not required to follow any standard (or wrote the patchwork prior to specs being finalized), we’re now in a period where existing packages need to be adjusted to reconcile the differences and run as expected natively.
IMO, to resist that change is to resist forward movement.
metadata can be obtained by importing the .json.js files which can be generated from .json files by prepending export default to them. I could even see it being part of this library’s distribution package.
I don’t fully understand your proposed workaround you gave in your reply, but the above statement is in agreement with the last sentence of my previous post 💯 .
ES6 support JSON importing with the following syntax: import * as data from ‘./example.json’
BTW, I did try this earlier and it fails with the same error as originally reported.
Regarding semver-compare , it does seem that it would be reasonable to inline or absorb into your project since it’s a single function. Just out of curiosity, is it necessary any more? It seems that you are only shipping one version of metadata, but the code supports 3 separate versions of the json?
I’m happy to test any changes you’re planning on implementing to support native module imports. I’m following this thread, so I’ll try to be responsive to test any updates.
Источник