Как создать json файл javascript
Перейти к содержимому

Как создать json файл javascript

  • автор:

Формат JSON, метод toJSON

Допустим, у нас есть сложный объект, и мы хотели бы преобразовать его в строку, чтобы отправить по сети или просто вывести для логирования.

Естественно, такая строка должна включать в себя все важные свойства.

Мы могли бы реализовать преобразование следующим образом:

…Но в процессе разработки добавляются новые свойства, старые свойства переименовываются и удаляются. Обновление такого toString каждый раз может стать проблемой. Мы могли бы попытаться перебрать свойства в нём, но что, если объект сложный, и в его свойствах имеются вложенные объекты? Мы должны были бы осуществить их преобразование тоже.

К счастью, нет необходимости писать код для обработки всего этого. У задачи есть простое решение.

JSON.stringify

JSON (JavaScript Object Notation) – это общий формат для представления значений и объектов. Его описание задокументировано в стандарте RFC 4627. Первоначально он был создан для JavaScript, но многие другие языки также имеют библиотеки, которые могут работать с ним. Таким образом, JSON легко использовать для обмена данными, когда клиент использует JavaScript, а сервер написан на Ruby/PHP/Java или любом другом языке.

JavaScript предоставляет методы:

  • JSON.stringify для преобразования объектов в JSON.
  • JSON.parse для преобразования JSON обратно в объект.

Например, здесь мы преобразуем через JSON.stringify данные студента:

Метод JSON.stringify(student) берёт объект и преобразует его в строку.

Полученная строка json называется JSON-форматированным или сериализованным объектом. Мы можем отправить его по сети или поместить в обычное хранилище данных.

Обратите внимание, что объект в формате JSON имеет несколько важных отличий от объектного литерала:

  • Строки используют двойные кавычки. Никаких одинарных кавычек или обратных кавычек в JSON. Так ‘John’ становится "John" .
  • Имена свойств объекта также заключаются в двойные кавычки. Это обязательно. Так age:30 становится "age":30 .

JSON.stringify может быть применён и к примитивам.

JSON поддерживает следующие типы данных:

  • Объекты
  • Массивы [ . ]
  • Примитивы:
    • строки,
    • числа,
    • логические значения true/false ,
    • null .

    JSON является независимой от языка спецификацией для данных, поэтому JSON.stringify пропускает некоторые специфические свойства объектов JavaScript.

    • Свойства-функции (методы).
    • Символьные ключи и значения.
    • Свойства, содержащие undefined .

    Обычно это нормально. Если это не то, чего мы хотим, то скоро мы увидим, как можно настроить этот процесс.

    Самое замечательное, что вложенные объекты поддерживаются и конвертируются автоматически.

    Важное ограничение: не должно быть циклических ссылок.

    Здесь преобразование завершается неудачно из-за циклической ссылки: room.occupiedBy ссылается на meetup , и meetup.place ссылается на room :

    Исключаем и преобразуем: replacer

    Полный синтаксис JSON.stringify :

    В большинстве случаев JSON.stringify используется только с первым аргументом. Но если нам нужно настроить процесс замены, например, отфильтровать циклические ссылки, то можно использовать второй аргумент JSON.stringify .

    Если мы передадим ему массив свойств, будут закодированы только эти свойства.

    Здесь мы, наверное, слишком строги. Список свойств применяется ко всей структуре объекта. Так что внутри participants – пустые объекты, потому что name нет в списке.

    Давайте включим в список все свойства, кроме room.occupiedBy , из-за которого появляется цикличная ссылка:

    Теперь всё, кроме occupiedBy , сериализовано. Но список свойств довольно длинный.

    К счастью, в качестве replacer мы можем использовать функцию, а не массив.

    Функция будет вызываться для каждой пары (key, value) , и она должна возвращать заменённое значение, которое будет использоваться вместо исходного. Или undefined , чтобы пропустить значение.

    В нашем случае мы можем вернуть value «как есть» для всего, кроме occupiedBy . Чтобы игнорировать occupiedBy , код ниже возвращает undefined :

    Обратите внимание, что функция replacer получает каждую пару ключ/значение, включая вложенные объекты и элементы массива. И она применяется рекурсивно. Значение this внутри replacer – это объект, который содержит текущее свойство.

    Первый вызов – особенный. Ему передаётся специальный «объект-обёртка»: <"": meetup>. Другими словами, первая (key, value) пара имеет пустой ключ, а значением является целевой объект в общем. Вот почему первая строка из примера выше будет ":[object Object]" .

    Идея состоит в том, чтобы дать как можно больше возможностей replacer – у него есть возможность проанализировать и заменить/пропустить даже весь объект целиком, если это необходимо.

    Форматирование: space

    Третий аргумент в JSON.stringify(value, replacer, space) – это количество пробелов, используемых для удобного форматирования.

    Ранее все JSON-форматированные объекты не имели отступов и лишних пробелов. Это нормально, если мы хотим отправить объект по сети. Аргумент space используется исключительно для вывода в удобочитаемом виде.

    Ниже space = 2 указывает JavaScript отображать вложенные объекты в несколько строк с отступом в 2 пробела внутри объекта:

    Третьим аргументом также может быть строка. В этом случае строка будет использоваться для отступа вместо ряда пробелов.

    Параметр space применяется исключительно для логирования и красивого вывода.

    Пользовательский «toJSON»

    Как и toString для преобразования строк, объект может предоставлять метод toJSON для преобразования в JSON. JSON.stringify автоматически вызывает его, если он есть.

    Как видим, date (1) стал строкой. Это потому, что все объекты типа Date имеют встроенный метод toJSON , который возвращает такую строку.

    Теперь давайте добавим собственную реализацию метода toJSON в наш объект room (2) :

    Как создать json файл javascript

    JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write and easy for machines to parse and generate. It is important to realize that, in JavaScript, JSON is a string and not an object.

    A basic overview can be found on the json.org

    (opens new window) website which also contains links to implementations of the standard in many different programming languages.

    # Parsing with a reviver function

    A reviver function can be used to filter or transform the value being parsed.

    This produces the following result:

    This is particularly useful when data must be sent that needs to be serialized/encoded when being transmitted with JSON, but one wants to access it deserialized/decoded. In the following example, a date was encoded to its ISO 8601 representation. We use the reviver function to parse this in a JavaScript Date .

    It is important to make sure the reviver function returns a useful value at the end of each iteration. If the reviver function returns undefined , no value or the execution falls off towards the end of the function, the property is deleted from the object. Otherwise, the property is redefined to be the return value.

    # Serializing a value

    A JavaScript value can be converted to a JSON string using the JSON.stringify function.

    1. value The value to convert to a JSON string.
    1. replacer A function that alters the behaviour of the stringification process or an array of String and Number objects that serve as a whitelist for filtering the properties of the value object to be included in the JSON string. If this value is null or is not provided, all properties of the object are included in the resulting JSON string.
    1. space For readability, the number of spaces used for indentation may be specified as the third parameter.

    Alternatively, a string value can be provided to use for indentation. For example, passing ‘\t’ will cause the tab character to be used for indentation.

    # Serializing and restoring class instances

    You can use a custom toJSON method and reviver function to transmit instances of your own class in JSON. If an object has a toJSON method, its result will be serialized instead of the object itself.

    This produces the a string with the following content:

    This produces the following object:

    # JSON versus JavaScript literals

    JSON stands for "JavaScript Object Notation", but it’s not JavaScript. Think of it as just a data serialization format that happens to be directly usable as a JavaScript literal. However, it is not advisable to directly run (i.e. through eval() ) JSON that is fetched from an external source. Functionally, JSON isn’t very different from XML or YAML – some confusion can be avoided if JSON is just imagined as some serialization format that looks very much like JavaScript.

    Even though the name implies just objects, and even though the majority of use cases through some kind of API always happen to be objects and arrays, JSON is not for just objects or arrays. The following primitive types are supported:

    • String (e.g. "Hello World!" )
    • Number (e.g. 42 )
    • Boolean (e.g. true )
    • The value null

    undefined is not supported in the sense that an undefined property will be omitted from JSON upon serialization. Therefore, there is no way to deserialize JSON and end up with a property whose value is undefined .

    The string "42" is valid JSON. JSON doesn’t always have to have an outer envelope of "<. >" or "[. ]" .

    While nome JSON is also valid JavaScript and some JavaScript is also valid JSON, there are some subtle differences between both languages and neither language is a subset of the other.

    Take the following JSON string as an example:

    This can be directly inserted into JavaScript. It will be syntactically valid and will yield the correct value:

    However, we know that "color" is a valid identifier name and the quotes around the property name can be omitted:

    We also know that we can use single quotes instead of double quotes:

    But, if we were to take both of these literals and treat them as JSON, neither will be syntactically valid JSON:

    JSON strictly requires all property names to be double quoted and string values to be double quoted as well.

    It’s common for JSON-newcomers to attempt to use code excerpts with JavaScript literals as JSON, and scratch their heads about the syntax errors they are getting from the JSON parser.

    More confusion starts arising when incorrect terminology is applied in code or in conversation.

    A common anti-pattern is to name variables that hold non-JSON values as "json":

    In the above example, response.data is a JSON string that is returned by some API. JSON stops at the HTTP response domain. The variable with the "json" misnomer holds just a JavaScript value (could be an object, an array, or even a simple number!)

    A less confusing way to write the above is:

    Developers also tend to throw the phrase "JSON object" around a lot. This also leads to confusion. Because as mentioned above, a JSON string doesn’t have to hold an object as a value. "JSON string" is a better term. Just like "XML string" or "YAML string". You get a string, you parse it, and you end up with a value.

    # Serializing with a replacer function

    A replacer function can be used to filter or transform values being serialized.

    This produces the following string:

    # Parsing a simple JSON string

    The JSON.parse() method parses a string as JSON and returns a JavaScript primitive, array or object:

    # Cyclic object values

    Not all objects can be converted to a JSON string. When an object has cyclic self-references, the conversion will fail.

    This is typically the case for hierarchical data structures where parent and child both reference each other:

    As soon as the process detects a cycle, the exception is raised. If there were no cycle detection, the string would be infinitely long.

    # Syntax
    • JSON.parse(input[, reviver])
    • JSON.stringify(value[, replacer[, space]])
    # Parameters
    Parameter Details
    JSON.parse Parse a JSON string
    input(string) JSON string to be parsed.
    reviver(function) Prescribes a transformation for the input JSON string.
    JSON.stringify Serialize a serializable value
    value(string) Value to be serialized according to the JSON specification.
    replacer(function or String[] or Number[]) Selectively includes certain properties of the value object.
    space(String or Number ) If a number is provided, then space number of whitespaces will be inserted of readability. If a string is provided, the string (first 10 characters) will be used as whitespaces.
    # Remarks

    The JSON utility methods were first standardized in ECMAScript 5.1 §15.12

    The format was formally defined in The application/json Media Type for JSON (RFC 4627 July 2006) which was later updated in The JSON Data Interchange Format (RFC 7158 March 2013, ECMA-404

    (opens new window) October 2013 and RFC 7159 March 2014).

    To make these methods available in old browsers such as Internet Explorer 8, use Douglas Crockford’s json2.js

    Working with JSON

    JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications (e.g., sending some data from the server to the client, so it can be displayed on a web page, or vice versa). You’ll come across it quite often, so in this article, we give you all you need to work with JSON using JavaScript, including parsing JSON so you can access data within it, and creating JSON.

    Prerequisites: Basic computer literacy, a basic understanding of HTML and CSS, familiarity with JavaScript basics (see First steps and Building blocks) and OOJS basics (see Introduction to objects).
    Objective: To understand how to work with data stored in JSON, and create your own JSON strings.

    No, really, what is JSON?

    JSON is a text-based data format following JavaScript object syntax, which was popularized by Douglas Crockford. Even though it closely resembles JavaScript object literal syntax, it can be used independently from JavaScript, and many programming environments feature the ability to read (parse) and generate JSON.

    JSON exists as a string — useful when you want to transmit data across a network. It needs to be converted to a native JavaScript object when you want to access the data. This is not a big issue — JavaScript provides a global JSON object that has methods available for converting between the two.

    Note: Converting a string to a native object is called deserialization, while converting a native object to a string so it can be transmitted across the network is called serialization.

    A JSON string can be stored in its own file, which is basically just a text file with an extension of .json , and a MIME type of application/json .

    JSON structure

    As described above, JSON is a string whose format very much resembles JavaScript object literal format. You can include the same basic data types inside JSON as you can in a standard JavaScript object — strings, numbers, arrays, booleans, and other object literals. This allows you to construct a data hierarchy, like so:

    If we loaded this string into a JavaScript program and parsed it into a variable called superHeroes for example, we could then access the data inside it using the same dot/bracket notation we looked at in the JavaScript object basics article. For example:

    To access data further down the hierarchy, you have to chain the required property names and array indexes together. For example, to access the third superpower of the second hero listed in the members list, you’d do this:

    1. First, we have the variable name — superHeroes .
    2. Inside that, we want to access the members property, so we use [«members»] .
    3. members contains an array populated by objects. We want to access the second object inside the array, so we use [1] .
    4. Inside this object, we want to access the powers property, so we use [«powers»] .
    5. Inside the powers property is an array containing the selected hero’s superpowers. We want the third one, so we use [2] .

    Note: We’ve made the JSON seen above available inside a variable in our JSONTest.html example (see the source code). Try loading this up and then accessing data inside the variable via your browser’s JavaScript console.

    Arrays as JSON

    Above we mentioned that JSON text basically looks like a JavaScript object inside a string. We can also convert arrays to/from JSON. Below is also valid JSON, for example:

    The above is perfectly valid JSON. You’d just have to access array items (in its parsed version) by starting with an array index, for example [0][«powers»][0] .

    Other notes

    • JSON is purely a string with a specified data format — it contains only properties, no methods.
    • JSON requires double quotes to be used around strings and property names. Single quotes are not valid other than surrounding the entire JSON string.
    • Even a single misplaced comma or colon can cause a JSON file to go wrong, and not work. You should be careful to validate any data you are attempting to use (although computer-generated JSON is less likely to include errors, as long as the generator program is working correctly). You can validate JSON using an application like JSONLint.
    • JSON can actually take the form of any data type that is valid for inclusion inside JSON, not just arrays or objects. So for example, a single string or number would be valid JSON.
    • Unlike in JavaScript code in which object properties may be unquoted, in JSON only quoted strings may be used as properties.

    Active learning: Working through a JSON example

    So, let’s work through an example to show how we could make use of some JSON formatted data on a website.

    Getting started

    To begin with, make local copies of our heroes.html and style.css files. The latter contains some simple CSS to style our page, while the former contains some very simple body HTML, plus a <script> element to contain the JavaScript code we will be writing in this exercise:

    We are going to load the JSON into our script, and use some nifty DOM manipulation to display it, like this:

    Image of a document titled "Super hero squad" (in a fancy font) and subtitled "Hometown: Metro City // Formed: 2016". Three columns below the heading are titled "Molecule Man", "Madame Uppercut", and "Eternal Flame", respectively. Each column lists the hero

    Top-level function

    The top-level function looks like this:

    To obtain the JSON, we use an API called Fetch. This API allows us to make network requests to retrieve resources from a server via JavaScript (e.g. images, text, JSON, even HTML snippets), meaning that we can update small sections of content without having to reload the entire page.

    In our function, the first four lines use the Fetch API to fetch the JSON from the server:

    • we declare the requestURL variable to store the GitHub URL
    • we use the URL to initialize a new Request object.
    • we make the network request using the fetch() function, and this returns a Response object
    • we retrieve the response as JSON using the json() function of the Response object.

    Note: The fetch() API is asynchronous. We’ll learn a lot about asynchronous functions in the next module, but for now, we’ll just say that we need to add the keyword async before the name of the function that uses the fetch API, and add the keyword await before the calls to any asynchronous functions.

    After all that, the superHeroes variable will contain the JavaScript object based on the JSON. We are then passing that object to two function calls — the first one fills the <header> with the correct data, while the second one creates an information card for each hero on the team, and inserts it into the <section> .

    Populating the header

    Now that we’ve retrieved the JSON data and converted it into a JavaScript object, let’s make use of it by writing the two functions we referenced above. First of all, add the following function definition below the previous code:

    Here we first create an h1 element with createElement() , set its textContent to equal the squadName property of the object, then append it to the header using appendChild() . We then do a very similar operation with a paragraph: create it, set its text content and append it to the header. The only difference is that its text is set to a template literal containing both the homeTown and formed properties of the object.

    Creating the hero information cards

    Next, add the following function at the bottom of the code, which creates and displays the superhero cards:

    To start with, we store the members property of the JavaScript object in a new variable. This array contains multiple objects that contain the information for each hero.

    Next, we use a for. of loop to loop through each object in the array. For each one, we:

    1. Create several new elements: an <article> , an <h2> , three <p> s, and a <ul> .
    2. Set the <h2> to contain the current hero’s name .
    3. Fill the three paragraphs with their secretIdentity , age , and a line saying «Superpowers:» to introduce the information in the list.
    4. Store the powers property in another new constant called superPowers — this contains an array that lists the current hero’s superpowers.
    5. Use another for. of loop to loop through the current hero’s superpowers — for each one we create an <li> element, put the superpower inside it, then put the listItem inside the <ul> element ( myList ) using appendChild() .
    6. The very last thing we do is to append the <h2> , <p> s, and <ul> inside the <article> ( myArticle ), then append the <article> inside the <section> . The order in which things are appended is important, as this is the order they will be displayed inside the HTML.

    Note: If you are having trouble getting the example to work, try referring to our heroes-finished.html source code (see it running live also.)

    Note: If you are having trouble following the dot/bracket notation we are using to access the JavaScript object, it can help to have the superheroes.json file open in another tab or your text editor, and refer to it as you look at our JavaScript. You should also refer back to our JavaScript object basics article for more information on dot and bracket notation.

    Calling the top-level function

    Finally, we need to call our top-level populate() function:

    Converting between objects and text

    The above example was simple in terms of accessing the JavaScript object, because we converted the network response directly into a JavaScript object using response.json() .

    But sometimes we aren’t so lucky — sometimes we receive a raw JSON string, and we need to convert it to an object ourselves. And when we want to send a JavaScript object across the network, we need to convert it to JSON (a string) before sending it. Luckily, these two problems are so common in web development that a built-in JSON object is available in browsers, which contains the following two methods:

      : Accepts a JSON string as a parameter, and returns the corresponding JavaScript object. : Accepts an object as a parameter, and returns the equivalent JSON string.

    You can see the first one in action in our heroes-finished-json-parse.html example (see the source code) — this does exactly the same thing as the example we built up earlier, except that:

    • we retrieve the response as text rather than JSON, by calling the text() method of the response
    • we then use parse() to convert the text to a JavaScript object.

    The key snippet of code is here:

    As you might guess, stringify() works the opposite way. Try entering the following lines into your browser’s JavaScript console one by one to see it in action:

    Here we’re creating a JavaScript object, then checking what it contains, then converting it to a JSON string using stringify() — saving the return value in a new variable — then checking it again.

    Test your skills!

    You’ve reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you’ve retained this information before you move on — see Test your skills: JSON.

    Summary

    In this article, we’ve given you a simple guide to using JSON in your programs, including how to create and parse JSON, and how to access data locked inside it. In the next article, we’ll begin looking at object-oriented JavaScript.

    Creating .json file and storing data in it with JavaScript?

    I have a back-end JavaScript file that runs on node.js . It do some stuff using async.series and yields the final dictionary(object) with data I need on my front-end. I now how to read a .json file and convert it into the JavaScript object, but I do not know create .json file with back-end JavaScript and how to store some data in it.

    Could anyone please tell me the right way to do this.

    Here is the dictionary(object) that I need to convert and store to the .json file.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *