Json отличие от javascript

JSON

Объект JSON содержит методы для разбора объектной нотации JavaScript (JavaScript Object Notation — сокращённо JSON) и преобразования значений в JSON. Его нельзя вызвать как функцию или сконструировать как объект, и кроме своих двух методов он не содержит никакой интересной функциональности.

Описание

Объектная нотация JavaScript

JSON является синтаксисом для сериализации объектов, массивов, чисел, строк логических значений и значения null . Он основывается на синтаксисе JavaScript, однако всё же отличается от него: не каждый код на JavaScript является JSON, и не каждый JSON является кодом на JavaScript. Смотрите также статью JSON: подмножество JavaScript, которым он не является (на английском).

Только ограниченный набор символов может быть заэкранирован; некоторые управляющие символы запрещены; разрешены юникодные символы разделительной линии (U+2028) и разделительного параграфа (U+2029); строки должны быть заключены в двойные кавычки. Смотрите следующий пример, в котором метод JSON.parse() отрабатывает без проблем, а при вычислении кода как JavaScript выбрасывается исключение SyntaxError :

var code = '"\u2028\u2029"'; JSON.parse(code); // работает eval(code); // ошибка 

Ниже представлен полный синтаксис JSON:

JSON = null or true or false or JSONNumber or JSONString or JSONObject or JSONArray JSONNumber = - PositiveNumber or PositiveNumber PositiveNumber = DecimalNumber or DecimalNumber . Digits or DecimalNumber . Digits ExponentPart or DecimalNumber ExponentPart DecimalNumber = 0 or OneToNine Digits ExponentPart = e Exponent or E Exponent Exponent = Digits or + Digits or - Digits Digits = Digit or Digits Digit Digit = 0 through 9 OneToNine = 1 through 9 JSONString = "" or " StringCharacters " StringCharacters = StringCharacter or StringCharacters StringCharacter StringCharacter = any character except " or \ or U+0000 through U+001F or EscapeSequence EscapeSequence = \" or \/ or \\ or \b or \f or \n or \r or \t or \u HexDigit HexDigit HexDigit HexDigit HexDigit = 0 through 9 or A through F or a through f JSONObject = < >or < Members >Members = JSONString : JSON or Members , JSONString : JSON JSONArray = [ ] or [ ArrayElements ] ArrayElements = JSON or ArrayElements , JSON

Во всех продукциях могут присутствовать незначащие пробельные символы, за исключением продукций ЧислоJSON (числа не должны содержать пробелов) и СтрокаJSON (где они интерпретируются как часть строки или возбуждают ошибку). Пробельными символами считаются символы табуляции (U+0009), возврата каретки (U+000D), перевода строки (U+000A) и, собственно, пробела (U+0020).

Методы

Разбирает строку JSON, возможно с преобразованием получаемого значения и его свойств и возвращает разобранное значение.

Возвращает строку JSON, соответствующую указанному значению, возможно с включением только определённых свойств или с заменой значений свойств определяемым пользователем способом.

Полифил

Объект JSON не поддерживается старыми браузерами. Вы можете работать с ним, добавив следующий код в начало ваших скриптов, он позволяет использовать объект JSON в реализациях, которые его ещё не поддерживают (например, в Internet Explorer 6).

Следующий алгоритм имитирует работу настоящего объекта JSON :

if (!window.JSON)  window.JSON =  parse: function(sJSON)  return eval('(' + sJSON + ')'); >, stringify: function(vContent)  if (vContent instanceof Object)  var sOutput = ''; if (vContent.constructor === Array)  for (var nId = 0; nId  vContent.length; sOutput += this.stringify(vContent[nId]) + ',', nId++); return '[' + sOutput.substr(0, sOutput.length - 1) + ']'; > if (vContent.toString !== Object.prototype.toString)  return '"' + vContent.toString().replace(/"/g, '\\$&') + '"'; > for (var sProp in vContent)  sOutput += '"' + sProp.replace(/"/g, '\\$&') + '":' + this.stringify(vContent[sProp]) + ','; > return ' + sOutput.substr(0, sOutput.length - 1) + '>'; > return typeof vContent === 'string' ? '"' + vContent.replace(/"/g, '\\$&') + '"' : String(vContent); > >; > 

Более сложными известными полифилами для объекта JSON являются проекты JSON2 и JSON3.

Спецификации

Совместимость с браузерами

BCD tables only load in the browser

Смотрите также

Found a content problem with this page?

This page was last modified on 22 окт. 2022 г. by MDN contributors.

Your blueprint for a better internet.

Источник

JSON Vs. JavaScript: What is the Difference?

Web development relies on JavaScript, but what is JSON, and what does a JSON vs. JavaScript comparison look like? Understanding the technology behind the web is important for organizations that are looking to innovate and make the most out of available resources. Everything web-related is going to use JavaScript. However, JSON is more nuanced, and you may or may not need to use it.

JSON and JavaScript

Before we can really begin to compare JSON vs. JavaScript, we need to understand what JSON is and how it relates to JavaScript. Let’s review what JavaScript and JSON are and then compare and contrast them to see what their differences are.

What is JavaScript?

JavaScript is one of the core technologies of the World Wide Web alongside HTML and CSS. JavaScript brings web pages to life. Without it, modern web design would be static and boring. JavaScript is a programming language. It is probably the most important programming language because every aspect of web development is built off of it. This is why it is a core technology of the World Wide Web.

We are not going to spend a lot of time detailing what JavaScript is. There are a number of other resources on our website that you can explore that go into more detail regarding the specifics of JavaScript.

The information above is more than sufficient for our purpose of comparing JSON vs. JavaScript.

What is JSON?

JSON is short for JavaScript Object Notation. So is JSON JavaScript? Not exactly. JSON is a data format that is independent of any programming language, although it is derived from JavaScript. The bulk of modern programming languages contain code that can generate and parse JSON data.

  • It is a lightweight format for storing and transporting data
  • The syntax is self-describing, making it easy for humans to read and understand
  • Typically, JSON is used when data is sent from a server to a web page

JSON data is structured in two basic ways: a key/value pair or a collection of such pairs, or an ordered list. JSON allows six different types of data to be stored or transported, including:

As you can see, JavaScript and JSON are two completely different things. While JSON is derived from JavaScript, the two are not exactly comparable in any way. However, we can compare JSON to JavaScript objects. These two are more closely related, and they offer us a better comparison.

What are JavaScript Objects?

JavaScript objects are also used to store data. All JavaScript values are actually objects with the exception of primitive data types, null, Boolean, number, string, symbol, and undefined. JavaScript objects can get complex because they can contain a number of different primitive data combinations.

JavaScript objects are also structured in key/value pairs. They can be created by object constructor syntax, object literals, constructors, and prototypes. JavaScript objects are mutable. This means that you can change the value for a respective key in a key/value pair.

JSON Vs. JavaScript Objects: What are the Differences?

Before we look at the ways in which JSON and JavaScript objects differ, it is important to understand that JSON and JavaScript objects are far more similar than they are different. JSON is derived from JavaScript object literal syntax. In fact, the simplest explanation would be that JSON is JavaScript object literal syntax but with more restrictions.

JSON and JavaScript objects are both human-readable. They both give users a way to structure data, and they can both be used as the source for another source. When it comes to differences, JSON and JavaScript objects differ in a few key ways:

Language Dependency

One of the biggest differences between JSON and JavaScript objects is the dependency on a programming language. JavaScript objects are completely dependent on JavaScript. They wouldn’t work with any other programming language.

On the other hand, JSON is supported by more than 50 different programming languages, including popular languages such as:

This wide array of support makes JSON a flexible choice for data storage and transfer.

Text Only

JSON data can only be presented in text. You cannot add comments or other lines of code to JSON. This rigidity is the reason why so many other programming languages can generate and parse JSON.

JavaScript objects can include other code such as functions and methods. This allows for a greater degree of complexity and function.

String Vs. Object

The last major difference between JSON and JavaScript objects is the way they are presented. JSON is presented in a string. These are referred to as JSON strings. JavaScript objects can contain strings, but they are, as their name suggests, objects instead of strings. Objects are more complex than strings.

Final Thoughts

The differences between JSON and JavaScript objects are slight and nuanced. Likely, your organization won’t have to worry about making a choice between these two unless you are a tech company working in web development.

If you need help determining what path is right for your organization, seek help from an app development partner. A partner can use their technical expertise and industry experience to help guide you through all of the critical decisions you will need to make, and they can help you understand nuanced comparisons like JSON vs. JavaScript objects.

Источник

Разница между объектом javascript и объектом JSON?

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

JSON расшифровывается как JavaScript Object Notation. По сути, это текстовый формат, который упрощает обмен данными между устройствами, такими как клиенты и серверы. Его происхождение основано на том, как работает объект JavaScript, поэтому в этом смысле он связан / близок к объекту JavaScript, но не полностью. Несмотря на то, что он возник из JavaScript, он широко используется на многих языках, таких как C, Ruby, Python, PHP, и это лишь некоторые из них. Из-за размера и простоты преобразования в структуру данных это своего рода отличная альтернатива другим форматам, таким как XML.

Очень хорошее преимущество использования JSON — это легкость его чтения.

Обратите внимание на приведенный выше фрагмент. Я создал объект JSON с несколькими парами ключ-значение. Клавиши находятся слева (имя, язык и хобби), а значения клавиш — справа. Это можно легко понять как объект для JavaScript и для всех, кто его читает.

Еще одно хорошее преимущество JSON — это возможность передавать значение или данные в объект JavaScript. Это можно просто сделать с помощью команды JavaScript, как показано ниже.

С помощью этой однострочной команды вы можете получить доступ к чему угодно из данных объекта. Итак, скажем, вы должны были получить значение имени, все, что вам нужно сделать, это просто ввести:

userInfo.name; // Использование записи через точку.

userInfo [«имя»] // Использование скобок

Еще одно хорошее преимущество — это то, что он компактнее, чем XML. Когда вы попытаетесь запустить ту же команду или сценарий с использованием XML, вы заметите, что передача XML может занять много времени, тогда как с JSON это происходит намного быстрее.

Давайте посмотрим, как пишутся строки JSON.

Внимательно посмотрите на ключи. Вы заметите, что они написаны в кавычках. Ключи также могут быть любой допустимой строкой. Значения JSON могут быть только одним из шести типов данных (строки, числа, объекты, массивы, логическое значение, null). С другой стороны, значения JavaScript могут быть любой допустимой структурой JavaScript.

В приведенном выше фрагменте вы могли заметить, что ключи не заключены в кавычки. Это типичный пример объекта JavaScript. Значения объекта JavaScript могут быть любого типа, включая функцию (которую вы НЕ МОЖЕТ выполнять с JSON. Взгляните на приведенный ниже фрагмент, показывающий действительный объект JavaScript.

В отличие от объекта JavaScript, объект JSON необходимо передать в переменную как строку, а затем проанализировать в JavaScript. Такой фреймворк, как jQuery, может быть очень полезен при синтаксическом анализе.

Есть довольно много инструментов, которые вы можете использовать для проверки вашего JSON-кода, и некоторые из них перечислены ниже:

· Представление JSON для Mozilla, Chrome и т. Д.

Посмотрите это пространство, чтобы узнать больше о работе с объектами JavaScript и JSON.

Источник

Читайте также:  Python parallel programming cookbook second edition
Оцените статью