Как мне на js создать json файл и сохранить туда данные, которые мне пришли с сервера?
Как мне на js создать json файл и сохранить туда данные, которые мне пришли с сервера? Я сделал запрос на сервер и мне пришел объект с данными и нужно эти данные записать в отдельный файл json формата.
Отслеживать
задан 19 дек 2021 в 14:09
29 7 7 бронзовых знаков
js бывает разный, о чём конкретно речь? Node или браузер?
19 дек 2021 в 14:21
Браузер скорее всего, точно
19 дек 2021 в 14:27
Из браузера создавать файлы невозможно по соображениям безопасности
19 дек 2021 в 14:27
19 дек 2021 в 14:29
@Roman, посмотрите модуль fs
19 дек 2021 в 14:29
1 ответ 1
Сортировка: Сброс на вариант по умолчанию
Если устраивает появление диалога для сохранения файла то можно сделать с помощью библиотеки file-saver. В качестве аргументов функция saveAs принимает blob и имя файла. Blob cоздается через экземпляр Blob в конструктор которого передаются данные (строка) и тип файла в данном случае application/json так же иногда не лишне будет передача charset для того чтобы не поломалась кодировка. Код приведенный ниже отработает если его перенести в html файл, в снипете вероятно по причине безопасности некоторый код не отрабатывает.
JSON.stringify(json, null, 2) — форматирует json с табуляцией в 2 пробела
How to create a Json File in memory from javascript object?
I have a backend endpoint that only accepts a json file. The user is supposed to upload a Json file and then the application submits this file to the endpoint and it works fine. Now I would like to use the same endpoint to upload json files created by the code, I would like for example to take the following javascript object
and transform it into a File object, so that I can submit it as a file, not as an object. I have tried to use the File Api constructor like this:
new File([< name: 'Brian', age: 40 >], "file.json", < type: "application/json" >);
but the endpoint does not accept it, I assume the first argument is not in the right format. should it be a blob instead?
JSON Syntax
The JSON syntax is a subset of the JavaScript syntax.
JSON Syntax Rules
JSON syntax is derived from JavaScript object notation syntax:
- Data is in name/value pairs
- Data is separated by commas
- Curly braces hold objects
- Square brackets hold arrays
JSON Data — A Name and a Value
JSON data is written as name/value pairs (aka key/value pairs).
A name/value pair consists of a field name (in double quotes), followed by a colon, followed by a value:
Example
JSON names require double quotes.
JSON — Evaluates to JavaScript Objects
The JSON format is almost identical to JavaScript objects.
In JSON, keys must be strings, written with double quotes:
JSON
In JavaScript, keys can be strings, numbers, or identifier names:
JavaScript
JSON Values
In JSON, values must be one of the following data types:
- a string
- a number
- an object
- an array
- a boolean
- null
In JavaScript values can be all of the above, plus any other valid JavaScript expression, including:
In JSON, string values must be written with double quotes:
JSON
In JavaScript, you can write string values with double or single quotes:
JavaScript
JavaScript Objects
Because JSON syntax is derived from JavaScript object notation, very little extra software is needed to work with JSON within JavaScript.
With JavaScript you can create an object and assign data to it, like this:
Example
You can access a JavaScript object like this:
Example
// returns John
person.name;
It can also be accessed like this:
Example
// returns John
person[«name»];
Data can be modified like this:
Example
person.name = «Gilbert»;
It can also be modified like this:
Example
person[«name»] = «Gilbert»;
You will learn how to convert JavaScript objects into JSON later in this tutorial.
JavaScript Arrays as JSON
The same way JavaScript objects can be written as JSON, JavaScript arrays can also be written as JSON.
You will learn more about objects and arrays later in this tutorial.
JSON Files
- The file type for JSON files is «.json»
- The MIME type for JSON text is «application/json»
COLOR PICKER


Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning.
Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness
of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Creating a package.json file
You can add a package.json file to your package to make it easy for others to manage and install. Packages published to the registry must contain a package.json file.
A package.json file:
- lists the packages your project depends on
- specifies versions of a package that your project can use using semantic versioning rules
- makes your build reproducible, and therefore easier to share with other developers
Note: To make your package easier to find on the npm website, we recommend including a custom description in your package.json file.
package.json fields
Required name and version fields
A package.json file must contain «name» and «version» fields.
The «name» field contains your package’s name, and must be lowercase and one word, and may contain hyphens and underscores.
The «version» field must be in the form x.x.x and follow the semantic versioning guidelines.
Author field
If you want to include package author information in «author» field, use the following format (email and website are both optional):
Example
"name": "my-awesome-package","version": "1.0.0","author": "Your Name ">
Creating a new package.json file
You can create a package.json file by running a CLI questionnaire or creating a default package.json file.
Running a CLI questionnaire
To create a package.json file with values that you supply, use the npm init command.
- On the command line, navigate to the root directory of your package. cd /path/to/package
- Run the following command: npm init
- Answer the questions in the command line questionnaire.
Customizing the package.json questionnaire
If you expect to create many package.json files, you can customize the questions asked and fields created during the init process so all the package.json files contain a standard set of information.
- In your home directory, create a file called .npm-init.js .
- To add custom questions, using a text editor, add questions with the prompt function: module.exports = prompt(«what’s your favorite flavor of ice cream, buddy?», «I LIKE THEM ALL»);
- To add custom fields, using a text editor, add desired fields to the .npm-init.js file:
module.exports =customField: 'Example custom field',otherCustomField: 'This example field is really cool'>
To learn more about creating advanced npm init customizations, see the init-package-json GitHub repository.
Creating a default package.json file
To create a default package.json using information extracted from the current directory, use the npm init command with the —yes or -y flag. For a list of default values, see «Default values extracted from the current directory».
- On the command line, navigate to the root directory of your package. cd /path/to/package
- Run the following command: npm init —yes
Example
> npm init --yesWrote to /home/monatheoctocat/my_package/package.json:"name": "my_package","description": "","version": "1.0.0","scripts":"test": "echo \"Error: no test specified\" && exit 1">,"repository":"type": "git","url": "https://github.com/monatheoctocat/my_package.git">,"keywords": [],"author": "","license": "ISC","bugs":"url": "https://github.com/monatheoctocat/my_package/issues">,"homepage": "https://github.com/monatheoctocat/my_package">
Default values extracted from the current directory
- name : the current directory name
- version : always 1.0.0
- description : info from the README, or an empty string «»
- scripts : by default creates an empty test script
- keywords : empty
- author : empty
- license : ISC
- bugs : information from the current directory, if present
- homepage : information from the current directory, if present
Setting config options for the init command
You can set default config options for the init command. For example, to set the default author email, author name, and license, on the command line, run the following commands:
> npm set init-author-email "example-user@example.com"> npm set init-author-name "example_user"> npm set init-license "MIT"
5 contributors
