-
03.09.2017, 01:00
#1
Junior Member
- Регистрация
- 06.08.2017
- Адрес
- Krasnodar
- Сообщений
- 28
Ошибка JSON Parse Error. Func: «file.upload»
Добрый день! Подскажите пожалуйста, при загрузке файла (архива с сайтом в формате zip) размером в 1,92 GB через файловый менеджер ispmanager 5, загрузка доходит до 100% и выдает вот такую вот ошибку JSON Parse Error. Func: «file.upload» Не подскажите из за чего она может возникать и как ее решить?
В логах нечего об этом нет, что самое интересное.
-
03.09.2017, 02:53
#2
Senior Member
- Регистрация
- 09.04.2013
- Адрес
- Москва
- Сообщений
- 2,103
панель открывается через nginx или напрямую по 1500 порту?
-
03.09.2017, 03:21
#3
Junior Member
- Регистрация
- 06.08.2017
- Адрес
- Krasnodar
- Сообщений
- 28
Сообщение от Mobiaaa
панель открывается через nginx или напрямую по 1500 порту?
Напрямую через поддомен который направлен на IP самого VPS, а так да, по 1500 порту вот так: manager.site.ru:1500/ispmgr
-
03.09.2017, 03:40
#4
Junior Member
- Регистрация
- 06.08.2017
- Адрес
- Krasnodar
- Сообщений
- 28
Какой кстати максимальный размер у файлового менеджера ? Какой он может осилить через веб-интерфейс? Просто это не где не указано, к примеру если я архив в 20GB отправлю загружаться, он должен загрузиться или нет?
1 / 1 / 1
Регистрация: 07.03.2012
Сообщений: 78
1
30.03.2015, 10:00. Показов 3503. Ответов 1
Есть аякс
Javascript | ||
|
В модели обрабатываю функцией
PHP | ||
|
В контроллере вывожу результат
if($_POST) echo add_comment();
Но вот получается, что в аяксе идет потом ошибка в консоле вида
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 106 of the JSON data
Что это за ошибка, где косяк?
__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь
0
The JavaScript exceptions thrown by JSON.parse()
occur when string failed
to be parsed as JSON.
Message
SyntaxError: JSON.parse: unterminated string literal SyntaxError: JSON.parse: bad control character in string literal SyntaxError: JSON.parse: bad character in string literal SyntaxError: JSON.parse: bad Unicode escape SyntaxError: JSON.parse: bad escape character SyntaxError: JSON.parse: unterminated string SyntaxError: JSON.parse: no number after minus sign SyntaxError: JSON.parse: unexpected non-digit SyntaxError: JSON.parse: missing digits after decimal point SyntaxError: JSON.parse: unterminated fractional number SyntaxError: JSON.parse: missing digits after exponent indicator SyntaxError: JSON.parse: missing digits after exponent sign SyntaxError: JSON.parse: exponent part is missing a number SyntaxError: JSON.parse: unexpected end of data SyntaxError: JSON.parse: unexpected keyword SyntaxError: JSON.parse: unexpected character SyntaxError: JSON.parse: end of data while reading object contents SyntaxError: JSON.parse: expected property name or '}' SyntaxError: JSON.parse: end of data when ',' or ']' was expected SyntaxError: JSON.parse: expected ',' or ']' after array element SyntaxError: JSON.parse: end of data when property name was expected SyntaxError: JSON.parse: expected double-quoted property name SyntaxError: JSON.parse: end of data after property name when ':' was expected SyntaxError: JSON.parse: expected ':' after property name in object SyntaxError: JSON.parse: end of data after property value in object SyntaxError: JSON.parse: expected ',' or '}' after property value in object SyntaxError: JSON.parse: expected ',' or '}' after property-value pair in object literal SyntaxError: JSON.parse: property names must be double-quoted strings SyntaxError: JSON.parse: expected property name or '}' SyntaxError: JSON.parse: unexpected character SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data
Error type
What went wrong?
JSON.parse()
parses a string as JSON. This string has to be valid JSON
and will throw this error if incorrect syntax was encountered.
Examples
JSON.parse() does not allow trailing commas
Both lines will throw a SyntaxError:
JSON.parse("[1, 2, 3, 4,]");
JSON.parse('{"foo": 1,}');
// SyntaxError JSON.parse: unexpected character
// at line 1 column 14 of the JSON data
Omit the trailing commas to parse the JSON correctly:
JSON.parse("[1, 2, 3, 4]");
JSON.parse('{"foo": 1}');
Property names must be double-quoted strings
You cannot use single-quotes around properties, like ‘foo’.
JSON.parse("{'foo': 1}");
// SyntaxError: JSON.parse: expected property name or '}'
// at line 1 column 2 of the JSON data
Instead write «foo»:
JSON.parse('{"foo": 1}');
Leading zeros and decimal points
You cannot use leading zeros, like 01, and decimal points must be followed by at least
one digit.
JSON.parse('{"foo": 01}');
// SyntaxError: JSON.parse: expected ',' or '}' after property value
// in object at line 1 column 2 of the JSON data
JSON.parse('{"foo": 1.}');
// SyntaxError: JSON.parse: unterminated fractional number
// at line 1 column 2 of the JSON data
Instead write just 1 without a zero and use at least one digit after a decimal point:
JSON.parse('{"foo": 1}');
JSON.parse('{"foo": 1.0}');
See also
I get error on running Countries.
CMD:
curl -i -d '{"Code":"FR","Name":"France"}' http://127.0.0.1:8080/countries
Error:
HTTP/1.1 500 Internal Server Error
Content-Type: application/json
X-Powered-By: go-json-rest
Date: Fri, 12 Dec 2014 04:29:59 GMT
Content-Length: 71
{
"Error": "invalid character '\'' looking for beginning of value"
}
JQuery:
$.post('http://localhost:8080/countries', {"Code":"FR","Name":"France"}, function(data) { console.log(data) });
Error:
{
"Error": "invalid character 'C' looking for beginning of value"
}
After I checked the source, I found the problem is parsing json on here.
I am appreciated if you could help me.
This is weird, I’ve just tried this example, and it’s working on my machine.
Could you provide more information ? like the version of Go ? of Go-Json-Rest ? …
Thank you for your fast reply!
Go version: go version go1.3.3 windows/386
Go-Json-Rest: latest
I never tried the curl command line on Windows, my bet is on the string escaping.
If you find a working curl command on Windows, could you let me know ? I think that could be a nice addition to the documentation.
If jQuery is failing too, I doubt it’s an escaping issue. I suspect the payload go-json-rest receives is not as it seems. Please dump r.Body in PostCountry()
I just test on ubuntu but it still not work with jQuery.
Go version: go version go1.2.1 linux/amd64
Go-Json-Rest: latest
Curl:
curl -i -d '{"Code":"FR","Name":"France"}' http://127.0.0.1:8080/countries
Success:
HTTP/1.1 200 OK
Content-Type: application/json
X-Powered-By: go-json-rest
Date: Fri, 12 Dec 2014 08:02:17 GMT
Content-Length: 38
{
"Code": "FR",
"Name": "France"
}
jQuery:
$.post('http://localhost:8080/countries', {"Code":"FR","Name":"France"}, function(data) { console.log(data) });
Error:
{
"Error": "invalid character 'C' looking for beginning of value"
}
Here is the result I tested on POSTMAN (chrome plugin):
Url: http://localhost:8080/countries
Method: POST
Mode: form-data
Data:
Code FR Text
Name France Text
Result:
{
"Error": "invalid character '-' in numeric literal"
}
Url: http://localhost:8080/countries
Method: POST
Mode: raw
Data:
Code FR Text
Name France Text
Result:
{
"Code": "FR",
"Name": "France"
}
It seems that it can only work on raw post.
Right, a JSON REST API should speak JSON, not form encoded data.
Also the Content-type header for these payload must be «application/json».
In Go-Json-Rest examples, I usually set the EnableRelaxedContentType: true
option in order to be more tolerant while developing. But really, your POST request payload must be JSON with Content-type: application/json
rest.Request
inherits from http.Request
, so I can get the form data by FormValue
.
It is good to add some examples using form data to help newbie like me
func PostCountry(w rest.ResponseWriter, r *rest.Request) {
country := Country{}
country.Code = r.FormValue("Code")
country.Name = r.FormValue("Name")
/*err := r.DecodeJsonPayload(&country)
if err != nil {
rest.Error(w, err.Error(), http.StatusInternalServerError)
return
}*/
if country.Code == "" {
rest.Error(w, "country code required", 400)
return
}
if country.Name == "" {
rest.Error(w, "country name required", 400)
return
}
lock.Lock()
store[country.Code] = &country
lock.Unlock()
w.WriteJson(&country)
}
I think this is more relevant to the general use of net/http than go-json-rest, but it may be good to have this around as an example. Thanks!
Overview¶
Base type¶
All exceptions inherit from class json::exception
(which in turn inherits from std::exception
). It is used as the base class for all exceptions thrown by the basic_json
class. This class can hence be used as «wildcard» to catch exceptions.
Switch off exceptions¶
Exceptions are used widely within the library. They can, however, be switched off with either using the compiler flag -fno-exceptions
or by defining the symbol JSON_NOEXCEPTION
. In this case, exceptions are replaced by abort()
calls. You can further control this behavior by defining JSON_THROW_USER
(overriding throw
), JSON_TRY_USER
(overriding try
), and JSON_CATCH_USER
(overriding catch
).
Note that JSON_THROW_USER
should leave the current scope (e.g., by throwing or aborting), as continuing after it may yield undefined behavior.
Example
The code below switches off exceptions and creates a log entry with a detailed error message in case of errors.
#include <iostream>
#define JSON_TRY_USER if(true)
#define JSON_CATCH_USER(exception) if(false)
#define JSON_THROW_USER(exception)
{std::clog << "Error in " << __FILE__ << ":" << __LINE__
<< " (function " << __FUNCTION__ << ") - "
<< (exception).what() << std::endl;
std::abort();}
#include <nlohmann/json.hpp>
Note the explanatory what()
string of exceptions is not available for MSVC if exceptions are disabled, see #2824.
See documentation of JSON_TRY_USER
, JSON_CATCH_USER
and JSON_THROW_USER
for more information.
Extended diagnostic messages¶
Exceptions in the library are thrown in the local context of the JSON value they are detected. This makes detailed diagnostics messages, and hence debugging, difficult.
Example
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
json j;
j["address"]["street"] = "Fake Street";
j["address"]["housenumber"] = "12";
try
{
int housenumber = j["address"]["housenumber"];
}
catch (json::exception& e)
{
std::cout << e.what() << 'n';
}
}
Output:
[json.exception.type_error.302] type must be number, but is string
This exception can be hard to debug if storing the value "12"
and accessing it is further apart.
To create better diagnostics messages, each JSON value needs a pointer to its parent value such that a global context (i.e., a path from the root value to the value that lead to the exception) can be created. That global context is provided as JSON Pointer.
As this global context comes at the price of storing one additional pointer per JSON value and runtime overhead to maintain the parent relation, extended diagnostics are disabled by default. They can, however, be enabled by defining the preprocessor symbol JSON_DIAGNOSTICS
to 1
before including json.hpp
.
Example
#include <iostream>
# define JSON_DIAGNOSTICS 1
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
json j;
j["address"]["street"] = "Fake Street";
j["address"]["housenumber"] = "12";
try
{
int housenumber = j["address"]["housenumber"];
}
catch (json::exception& e)
{
std::cout << e.what() << 'n';
}
}
Output:
[json.exception.type_error.302] (/address/housenumber) type must be number, but is string
Now the exception message contains a JSON Pointer /address/housenumber
that indicates which value has the wrong type.
See documentation of JSON_DIAGNOSTICS
for more information.
Parse errors¶
This exception is thrown by the library when a parse error occurs. Parse errors can occur during the deserialization of JSON text, CBOR, MessagePack, as well as when using JSON Patch.
Exceptions have ids 1xx.
Byte index
Member byte
holds the byte index of the last read character in the input file.
For an input with n bytes, 1 is the index of the first character and n+1 is the index of the terminating null byte or the end of file. This also holds true when reading a byte vector (CBOR or MessagePack).
Example
The following code shows how a parse_error
exception can be caught.
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
try
{
// parsing input with a syntax error
json::parse("[1,2,3,]");
}
catch (json::parse_error& e)
{
// output exception information
std::cout << "message: " << e.what() << 'n'
<< "exception id: " << e.id << 'n'
<< "byte position of error: " << e.byte << std::endl;
}
}
Output:
message: [json.exception.parse_error.101] parse error at line 1, column 8: syntax error while parsing value - unexpected ']'; expected '[', '{', or a literal
exception id: 101
byte position of error: 8
json.exception.parse_error.101¶
This error indicates a syntax error while deserializing a JSON text. The error message describes that an unexpected token (character) was encountered, and the member byte
indicates the error position.
Example message
Input ended prematurely:
[json.exception.parse_error.101] parse error at 2: unexpected end of input; expected string literal
No input:
[json.exception.parse_error.101] parse error at line 1, column 1: syntax error while parsing value - unexpected end of input; expected '[', '{', or a literal
Control character was not escaped:
[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - invalid string: control character U+0009 (HT) must be escaped to u0009 or \; last read: '"<U+0009>'"
String was not closed:
[json.exception.parse_error.101] parse error at line 1, column 2: syntax error while parsing value - invalid string: missing closing quote; last read: '"'
Invalid number format:
[json.exception.parse_error.101] parse error at line 1, column 3: syntax error while parsing value - invalid number; expected '+', '-', or digit after exponent; last read: '1E'
u
was not be followed by four hex digits:
[json.exception.parse_error.101] parse error at line 1, column 6: syntax error while parsing value - invalid string: 'u' must be followed by 4 hex digits; last read: '"u01"'
Invalid UTF-8 surrogate pair:
[json.exception.parse_error.101] parse error at line 1, column 13: syntax error while parsing value - invalid string: surrogate U+DC00..U+DFFF must follow U+D800..U+DBFF; last read: '"uD7FFuDC00'"
Invalid UTF-8 byte:
[json.exception.parse_error.101] parse error at line 3, column 24: syntax error while parsing value - invalid string: ill-formed UTF-8 byte; last read: '"vous 352t'
Tip
- Make sure the input is correctly read. Try to write the input to standard output to check if, for instance, the input file was successfully opened.
- Paste the input to a JSON validator like http://jsonlint.com or a tool like jq.
json.exception.parse_error.102¶
JSON uses the uxxxx
format to describe Unicode characters. Code points above 0xFFFF are split into two uxxxx
entries («surrogate pairs»). This error indicates that the surrogate pair is incomplete or contains an invalid code point.
Example message
parse error at 14: missing or wrong low surrogate
Note
This exception is not used any more. Instead json.exception.parse_error.101 with a more detailed description is used.
json.exception.parse_error.103¶
Unicode supports code points up to 0x10FFFF. Code points above 0x10FFFF are invalid.
Example message
parse error: code points above 0x10FFFF are invalid
Note
This exception is not used any more. Instead json.exception.parse_error.101 with a more detailed description is used.
json.exception.parse_error.104¶
RFC 6902 requires a JSON Patch document to be a JSON document that represents an array of objects.
Example message
[json.exception.parse_error.104] parse error: JSON patch must be an array of objects
json.exception.parse_error.105¶
An operation of a JSON Patch document must contain exactly one «op» member, whose value indicates the operation to perform. Its value must be one of «add», «remove», «replace», «move», «copy», or «test»; other values are errors.
Example message
[json.exception.parse_error.105] parse error: operation 'add' must have member 'value'
[json.exception.parse_error.105] parse error: operation 'copy' must have string member 'from'
[json.exception.parse_error.105] parse error: operation value 'foo' is invalid
json.exception.parse_error.106¶
An array index in a JSON Pointer (RFC 6901) may be 0
or any number without a leading 0
.
Example message
[json.exception.parse_error.106] parse error: array index '01' must not begin with '0'
json.exception.parse_error.107¶
A JSON Pointer must be a Unicode string containing a sequence of zero or more reference tokens, each prefixed by a /
character.
Example message
[json.exception.parse_error.107] parse error at byte 1: JSON pointer must be empty or begin with '/' - was: 'foo'
json.exception.parse_error.108¶
In a JSON Pointer, only ~0
and ~1
are valid escape sequences.
Example message
[json.exception.parse_error.108] parse error: escape character '~' must be followed with '0' or '1'
json.exception.parse_error.109¶
A JSON Pointer array index must be a number.
Example messages
[json.exception.parse_error.109] parse error: array index 'one' is not a number
[json.exception.parse_error.109] parse error: array index '+1' is not a number
json.exception.parse_error.110¶
When parsing CBOR or MessagePack, the byte vector ends before the complete value has been read.
Example message
[json.exception.parse_error.110] parse error at byte 5: syntax error while parsing CBOR string: unexpected end of input
[json.exception.parse_error.110] parse error at byte 2: syntax error while parsing UBJSON value: expected end of input; last byte: 0x5A
json.exception.parse_error.112¶
An unexpected byte was read in a binary format or length information is invalid (BSON).
Example messages
[json.exception.parse_error.112] parse error at byte 1: syntax error while parsing CBOR value: invalid byte: 0x1C
[json.exception.parse_error.112] parse error at byte 1: syntax error while parsing MessagePack value: invalid byte: 0xC1
[json.exception.parse_error.112] parse error at byte 4: syntax error while parsing BJData size: expected '#' after type information; last byte: 0x02
[json.exception.parse_error.112] parse error at byte 4: syntax error while parsing UBJSON size: expected '#' after type information; last byte: 0x02
[json.exception.parse_error.112] parse error at byte 10: syntax error while parsing BSON string: string length must be at least 1, is -2147483648
[json.exception.parse_error.112] parse error at byte 15: syntax error while parsing BSON binary: byte array length cannot be negative, is -1
json.exception.parse_error.113¶
While parsing a map key, a value that is not a string has been read.
Example messages
[json.exception.parse_error.113] parse error at byte 2: syntax error while parsing CBOR string: expected length specification (0x60-0x7B) or indefinite string type (0x7F); last byte: 0xFF
[json.exception.parse_error.113] parse error at byte 2: syntax error while parsing MessagePack string: expected length specification (0xA0-0xBF, 0xD9-0xDB); last byte: 0xFF
[json.exception.parse_error.113] parse error at byte 2: syntax error while parsing UBJSON char: byte after 'C' must be in range 0x00..0x7F; last byte: 0x82
json.exception.parse_error.114¶
The parsing of the corresponding BSON record type is not implemented (yet).
Example message
[json.exception.parse_error.114] parse error at byte 5: Unsupported BSON record type 0xFF
json.exception.parse_error.115¶
A UBJSON high-precision number could not be parsed.
Example message
[json.exception.parse_error.115] parse error at byte 5: syntax error while parsing UBJSON high-precision number: invalid number text: 1A
Iterator errors¶
This exception is thrown if iterators passed to a library function do not match the expected semantics.
Exceptions have ids 2xx.
Example
The following code shows how an invalid_iterator
exception can be caught.
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
try
{
// calling iterator::key() on non-object iterator
json j = "string";
json::iterator it = j.begin();
auto k = it.key();
}
catch (json::invalid_iterator& e)
{
// output exception information
std::cout << "message: " << e.what() << 'n'
<< "exception id: " << e.id << std::endl;
}
}
Output:
message: [json.exception.invalid_iterator.207] cannot use key() for non-object iterators
exception id: 207
json.exception.invalid_iterator.201¶
The iterators passed to constructor basic_json(InputIT first, InputIT last)
are not compatible, meaning they do not belong to the same container. Therefore, the range (first
, last
) is invalid.
Example message
[json.exception.invalid_iterator.201] iterators are not compatible
json.exception.invalid_iterator.202¶
In the erase or insert function, the passed iterator pos
does not belong to the JSON value for which the function was called. It hence does not define a valid position for the deletion/insertion.
Example messages
[json.exception.invalid_iterator.202] iterator does not fit current value
[json.exception.invalid_iterator.202] iterators first and last must point to objects
json.exception.invalid_iterator.203¶
Either iterator passed to function erase(IteratorType first, IteratorType last
) does not belong to the JSON value from which values shall be erased. It hence does not define a valid range to delete values from.
Example message
[json.exception.invalid_iterator.203] iterators do not fit current value
json.exception.invalid_iterator.204¶
When an iterator range for a primitive type (number, boolean, or string) is passed to a constructor or an erase function, this range has to be exactly (begin(),
end()),
because this is the only way the single stored value is expressed. All other ranges are invalid.
Example message
[json.exception.invalid_iterator.204] iterators out of range
json.exception.invalid_iterator.205¶
When an iterator for a primitive type (number, boolean, or string) is passed to an erase function, the iterator has to be the begin()
iterator, because it is the only way to address the stored value. All other iterators are invalid.
Example message
[json.exception.invalid_iterator.205] iterator out of range
json.exception.invalid_iterator.206¶
The iterators passed to constructor basic_json(InputIT first, InputIT last)
belong to a JSON null value and hence to not define a valid range.
Example message
[json.exception.invalid_iterator.206] cannot construct with iterators from null
json.exception.invalid_iterator.207¶
The key()
member function can only be used on iterators belonging to a JSON object, because other types do not have a concept of a key.
Example message
[json.exception.invalid_iterator.207] cannot use key() for non-object iterators
json.exception.invalid_iterator.208¶
The operator[]
to specify a concrete offset cannot be used on iterators belonging to a JSON object, because JSON objects are unordered.
Example message
[json.exception.invalid_iterator.208] cannot use operator[] for object iterators
json.exception.invalid_iterator.209¶
The offset operators (+
, -
, +=
, -=
) cannot be used on iterators belonging to a JSON object, because JSON objects are unordered.
Example message
[json.exception.invalid_iterator.209] cannot use offsets with object iterators
json.exception.invalid_iterator.210¶
The iterator range passed to the insert function are not compatible, meaning they do not belong to the same container. Therefore, the range (first
, last
) is invalid.
Example message
[json.exception.invalid_iterator.210] iterators do not fit
json.exception.invalid_iterator.211¶
The iterator range passed to the insert function must not be a subrange of the container to insert to.
Example message
[json.exception.invalid_iterator.211] passed iterators may not belong to container
json.exception.invalid_iterator.212¶
When two iterators are compared, they must belong to the same container.
Example message
[json.exception.invalid_iterator.212] cannot compare iterators of different containers
json.exception.invalid_iterator.213¶
The order of object iterators cannot be compared, because JSON objects are unordered.
Example message
[json.exception.invalid_iterator.213] cannot compare order of object iterators
json.exception.invalid_iterator.214¶
Cannot get value for iterator: Either the iterator belongs to a null value or it is an iterator to a primitive type (number, boolean, or string), but the iterator is different to begin()
.
Example message
[json.exception.invalid_iterator.214] cannot get value
Type errors¶
This exception is thrown in case of a type error; that is, a library function is executed on a JSON value whose type does not match the expected semantics.
Exceptions have ids 3xx.
Example
The following code shows how a type_error
exception can be caught.
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
try
{
// calling push_back() on a string value
json j = "string";
j.push_back("another string");
}
catch (json::type_error& e)
{
// output exception information
std::cout << "message: " << e.what() << 'n'
<< "exception id: " << e.id << std::endl;
}
}
Output:
message: [json.exception.type_error.308] cannot use push_back() with string
exception id: 308
json.exception.type_error.301¶
To create an object from an initializer list, the initializer list must consist only of a list of pairs whose first element is a string. When this constraint is violated, an array is created instead.
Example message
[json.exception.type_error.301] cannot create object from initializer list
json.exception.type_error.302¶
During implicit or explicit value conversion, the JSON type must be compatible to the target type. For instance, a JSON string can only be converted into string types, but not into numbers or boolean types.
Example messages
[json.exception.type_error.302] type must be object, but is null
[json.exception.type_error.302] type must be string, but is object
json.exception.type_error.303¶
To retrieve a reference to a value stored in a basic_json
object with get_ref
, the type of the reference must match the value type. For instance, for a JSON array, the ReferenceType
must be array_t &
.
Example messages
[json.exception.type_error.303] incompatible ReferenceType for get_ref, actual type is object
[json.exception.type_error.303] incompatible ReferenceType for get_ref, actual type is number"
json.exception.type_error.304¶
The at()
member functions can only be executed for certain JSON types.
Example messages
[json.exception.type_error.304] cannot use at() with string
[json.exception.type_error.304] cannot use at() with number
json.exception.type_error.305¶
The operator[]
member functions can only be executed for certain JSON types.
Example messages
[json.exception.type_error.305] cannot use operator[] with a string argument with array
[json.exception.type_error.305] cannot use operator[] with a numeric argument with object
json.exception.type_error.306¶
The value()
member functions can only be executed for certain JSON types.
Example message
[json.exception.type_error.306] cannot use value() with number
json.exception.type_error.307¶
The erase()
member functions can only be executed for certain JSON types.
Example message
[json.exception.type_error.307] cannot use erase() with string
json.exception.type_error.308¶
The push_back()
and operator+=
member functions can only be executed for certain JSON types.
Example message
[json.exception.type_error.308] cannot use push_back() with string
json.exception.type_error.309¶
The insert()
member functions can only be executed for certain JSON types.
Example messages
[json.exception.type_error.309] cannot use insert() with array
[json.exception.type_error.309] cannot use insert() with number
json.exception.type_error.310¶
The swap()
member functions can only be executed for certain JSON types.
Example message
[json.exception.type_error.310] cannot use swap() with number
json.exception.type_error.311¶
The emplace()
and emplace_back()
member functions can only be executed for certain JSON types.
Example messages
[json.exception.type_error.311] cannot use emplace() with number
[json.exception.type_error.311] cannot use emplace_back() with number
json.exception.type_error.312¶
The update()
member functions can only be executed for certain JSON types.
Example message
[json.exception.type_error.312] cannot use update() with array
json.exception.type_error.313¶
The unflatten
function converts an object whose keys are JSON Pointers back into an arbitrary nested JSON value. The JSON Pointers must not overlap, because then the resulting value would not be well-defined.
Example message
[json.exception.type_error.313] invalid value to unflatten
json.exception.type_error.314¶
The unflatten
function only works for an object whose keys are JSON Pointers.
Example message
Calling unflatten()
on an array [1,2,3]
:
[json.exception.type_error.314] only objects can be unflattened
json.exception.type_error.315¶
The unflatten()
function only works for an object whose keys are JSON Pointers and whose values are primitive.
Example message
Calling unflatten()
on an object {"/1", [1,2,3]}
:
[json.exception.type_error.315] values in object must be primitive
json.exception.type_error.316¶
The dump()
function only works with UTF-8 encoded strings; that is, if you assign a std::string
to a JSON value, make sure it is UTF-8 encoded.
Example message
Calling dump()
on a JSON value containing an ISO 8859-1 encoded string:
[json.exception.type_error.316] invalid UTF-8 byte at index 15: 0x6F
Tip
- Store the source file with UTF-8 encoding.
- Pass an error handler as last parameter to the
dump()
function to avoid this exception:json::error_handler_t::replace
will replace invalid bytes sequences withU+FFFD
json::error_handler_t::ignore
will silently ignore invalid byte sequences
json.exception.type_error.317¶
The dynamic type of the object cannot be represented in the requested serialization format (e.g. a raw true
or null
JSON object cannot be serialized to BSON)
Example messages
Serializing null
to BSON:
[json.exception.type_error.317] to serialize to BSON, top-level type must be object, but is null
Serializing [1,2,3]
to BSON:
[json.exception.type_error.317] to serialize to BSON, top-level type must be object, but is array
Tip
Encapsulate the JSON value in an object. That is, instead of serializing true
, serialize {"value": true}
Out of range¶
This exception is thrown in case a library function is called on an input parameter that exceeds the expected range, for instance in case of array indices or nonexisting object keys.
Exceptions have ids 4xx.
Example
The following code shows how an out_of_range
exception can be caught.
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
int main()
{
try
{
// calling at() for an invalid index
json j = {1, 2, 3, 4};
j.at(4) = 10;
}
catch (json::out_of_range& e)
{
// output exception information
std::cout << "message: " << e.what() << 'n'
<< "exception id: " << e.id << std::endl;
}
}
Output:
message: [json.exception.out_of_range.401] array index 4 is out of range
exception id: 401
json.exception.out_of_range.401¶
The provided array index i
is larger than size-1
.
Example message
array index 3 is out of range
json.exception.out_of_range.402¶
The special array index -
in a JSON Pointer never describes a valid element of the array, but the index past the end. That is, it can only be used to add elements at this position, but not to read it.
Example message
array index '-' (3) is out of range
json.exception.out_of_range.403¶
The provided key was not found in the JSON object.
json.exception.out_of_range.404¶
A reference token in a JSON Pointer could not be resolved.
Example message
unresolved reference token 'foo'
json.exception.out_of_range.405¶
The JSON Patch operations ‘remove’ and ‘add’ can not be applied to the root element of the JSON value.
Example message
JSON pointer has no parent
json.exception.out_of_range.406¶
A parsed number could not be stored as without changing it to NaN or INF.
Example message
number overflow parsing '10E1000'
json.exception.out_of_range.407¶
UBJSON and BSON only support integer numbers up to 9223372036854775807.
Example message
number overflow serializing '9223372036854775808'
Note
Since version 3.9.0, integer numbers beyond int64 are serialized as high-precision UBJSON numbers, and this exception does not further occur.
json.exception.out_of_range.408¶
The size (following #
) of an UBJSON array or object exceeds the maximal capacity.
Example message
excessive array size: 8658170730974374167
json.exception.out_of_range.409¶
Key identifiers to be serialized to BSON cannot contain code point U+0000, since the key is stored as zero-terminated c-string.
Example message
BSON key cannot contain code point U+0000 (at byte 2)
Further exceptions¶
This exception is thrown in case of errors that cannot be classified with the other exception types.
Exceptions have ids 5xx.
Example
The following code shows how an other_error
exception can be caught.
#include <iostream>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
using namespace nlohmann::literals;
int main()
{
try
{
// executing a failing JSON Patch operation
json value = R"({
"best_biscuit": {
"name": "Oreo"
}
})"_json;
json patch = R"([{
"op": "test",
"path": "/best_biscuit/name",
"value": "Choco Leibniz"
}])"_json;
value.patch(patch);
}
catch (json::other_error& e)
{
// output exception information
std::cout << "message: " << e.what() << 'n'
<< "exception id: " << e.id << std::endl;
}
}
Output:
message: [json.exception.other_error.501] unsuccessful: {"op":"test","path":"/best_biscuit/name","value":"Choco Leibniz"}
exception id: 501
json.exception.other_error.501¶
A JSON Patch operation ‘test’ failed. The unsuccessful operation is also printed.
Example message
Executing {"op":"test", "path":"/baz", "value":"bar"}
on {"baz": "qux"}
:
[json.exception.other_error.501] unsuccessful: {"op":"test","path":"/baz","value":"bar"}
Last update: December 19, 2022
$(document).ready(function(){ var imagesCount = 0; var maxImages = 6; var imagesList = {}; $(function () { var $image = $('#image'); $('#modal').on('shown.bs.modal', function () { $('.controls').hide(); $('.progress').hide(); $image.cropper({ built: function () { } }); }).on('hidden.bs.modal', function () { $('#submit-avatar-button').attr('disabled', 'true'); $image.attr('src', ''); $image.cropper('destroy'); }); $image.on('load', function(){ $image.cropper({ aspectRatio: 1, crop: function(data){ var d = $image.cropper('getData'); d.filename = $image.attr('src'); $('#avatar-data').val(JSON.stringify(d)); }, dragMode: 'crop', autoCrop: true, autoCropArea: 1, movable: false, scalable: false, zoomable: false, toggleDragModeOnDblclick: false, background: false, viewMode: 0, minCropBoxWidth: 100, minCropBoxHeight: 100 }); $('#submit-avatar-button').removeAttr('disabled'); }); $('.r_left').on('click', function(){ $image.cropper('rotate', -90); }); $('.r_right').on('click', function(){ $image.cropper('rotate', 90); }); $('#avatar-file').bind('change', function(){ var data = new FormData(); var error = ''; jQuery.each($('#avatar-file')[0].files, function(i, file) { if(file.name.length < 1) { error = error + ' Файл имеет неправильный размер! '; } data.append('file-'+i, file); }); $.ajax({ url: '/modules/upload_resize.php', data: data, cache: false, contentType: false, processData: false, type: 'POST',error: function (xhr, ajaxOptions, thrownError) { // alert(xhr.responseText); // alert(thrownError); }, xhr: function () { var xhr = $.ajaxSettings.xhr(); xhr.upload.addEventListener("progress", function (evt) { if (evt.lengthComputable) { var pB = $('.progress-bar'), percentComplete = evt.loaded / evt.total, progLabel = Math.round(percentComplete * 100) + "%"; pB.attr('style', 'width: '+progLabel); pB.text(progLabel); } }, false); return xhr; }, beforeSend: function () { $('.progress').show(); $('.controls').hide(); }, complete: function () { $('.progress-bar').text('Готово.'); $('.progress').delay(2000).fadeOut(500); $('.controls').show(); }, success: function(data){ $image.cropper('destroy'); $image.attr('src', data); } }); }); $('#submit-avatar-button').on('click', function (){ var imageList = $('#image_selection'), selectImage = imageList.children('#select'); var data = $('#avatar-data').attr('value'); $.ajax({ url: '/modules/addavatar.php', data: {'avatar-data':data}, type: 'POST', error: function(xhr, ajaxOptions, thrownError){ // alert(xhr.responseText); // alert(thrownError); }, success: function(data){ data = JSON.parse(data); var n = $('<li id="'+data.filename+'"></li>').insertBefore(selectImage); n.append('<img width="50" src="data:image/jpeg;base64,'+data.mini+'" />'); imagesList[data.filename] = true; $('<button type="button" class="btn btn-danger pull-right">Удалить</button>').appendTo(n) .on('click', function(){ imagesList[n.attr('id')] = false; n.remove(); imagesCount--; if (imagesCount > 0){ $('#sendimages').removeAttr('disabled'); } else {$('#sendimages').attr('disabled', true);} $('#image-selection-button').show(); }); imagesCount++; if (imagesCount>=maxImages){ $('#image-selection-button').hide(); } if (imagesCount > 0){ $('#sendimages').removeAttr('disabled'); } else {$('#sendimages').attr('disabled', true);} $('button[data-dismiss="modal"]').click(); } }); }); $('#sendimages').on('click', function (){ $('form#hidden').children('input[type="hidden"]').attr('value', JSON.stringify(imagesList)); $('form#hidden').children('input[type="submit"]').click(); }); }); }); function selectImage(){ $('#avatar-file').click(); }
http://jsonlint.com/ Ошибку показывает:
Error: Parse error on line 1: $(document).ready(fu ^ Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[', got 'undefined'
, а как ее исправить не могу допереть. Главное на реальном хосте работает все.