dropbox / json11 Goto Github PK
View Code? Open in Web Editor NEWA tiny JSON library for C++11.
License: MIT License
A tiny JSON library for C++11.
License: MIT License
Hi
I am using json11
in my project. And when i am trying to return a std::vector
of type long double
, json11
does not support it.
vector<long double>nav = select_from_fund_type(name);
json11::Json json(nav);
return crow::response(json.dump());
And here is the error i am receiving
error: no matching function for call to ‘json11::Json::Json(std::vector&)’
json11::Json json(nav);
^
In file included from main.cpp:6:0:
/usr/local/include/json11.hpp:119:5: note: candidate: template<class V, typename std::enable_if<std::is_constructible<json11::Json, typename V::value_type>::value, int>::type > json11::Json::Json(const V&)
Json(const V & v) : Json(array(v.begin(), v.end())) {}
^~~~
/usr/local/include/json11.hpp:119:5: note: template argument deduction/substitution failed:
/usr/local/include/json11.hpp:118:26: error: no type named ‘type’ in ‘struct std::enable_if<false, int>’
int>::type = 0>
^
/usr/local/include/json11.hpp:118:26: note: invalid template non-type parameter
/usr/local/include/json11.hpp:113:5: note: candidate: template<class M, typename std::enable_if<(std::is_constructible<std::basic_string, typename M::key_type>::value && std::is_constructible<json11::Json, typename M::mapped_type>::value), int>::type > json11::Json::Json(const M&)
Json(const M & m) : Json(object(m.begin(), m.end())) {}
^~~~
/usr/local/include/json11.hpp:113:5: note: template argument deduction/substitution failed:
/usr/local/include/json11.hpp:111:9: error: no type named ‘key_type’ in ‘class std::vector’
std::is_constructible<std::string, typename M::key_type>::value
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
&& std::is_constructible<Json, typename M::mapped_type>::value,
^~~~~~
/usr/local/include/json11.hpp:111:9: error: no type named ‘mapped_type’ in ‘class std::vector’
/usr/local/include/json11.hpp:112:26: note: invalid template non-type parameter
int>::type = 0>
^
/usr/local/include/json11.hpp:106:5: note: candidate: template<class T, class> json11::Json::Json(const T&)
Json(const T & t) : Json(t.to_json()) {}
^~~~
/usr/local/include/json11.hpp:106:5: note: template argument deduction/substitution failed:
/usr/local/include/json11.hpp:105:41: error: ‘to_json’ is not a member of ‘std::vector’
template <class T, class = decltype(&T::to_json)>
ifstream ifile;
int fsize;
char * inBuf;
ifile.open("res/test.json", ios_base::binary);
ifile.seekg(0, ios::end);
fsize = ifile.tellg();
ifile.seekg(0, ios::beg);
inBuf = new char[fsize];
ifile.read(inBuf, fsize);
string WINDOW_NAMES = (LPCSTR)ifile;
ifile.close();
int _json_data_ready = (int)WINDOW_NAMES;
Json my_json = Json::object{_json_data_ready};
while(looping == true) {
for (auto s : Json::array(my_json)) {
//code here.
};
};
Note: this code might generate at least 4 errors and 1 warning also note I am fairly new at C++ but at least I know how file objects work somewhat in Python in Visual Basic.
Anyway I want to know if I could do soemthing like this? when the Json would look something like this
{"detectlist": ["Cheat Engine 6.1", "Cheat Engine 6.2", "Cheat Engine 6.3", "Cheat Engine 6.4", "Cheat Engine 6.5", "Cheat Engine 6.6", "Cheat Engine 6.7", "Cheat Engine 6.8", "Cheat Engine 6.9", "Cheat Engine 7.0", "OllyDBG", "PEiD v0.95"]}
Note the json will always change and as such I dont want to always change my DLL just because the json changes as what would the point of the json be?
The behavior of std::cin.get() breaks parse_from_stdin() in test.cpp when /g++ 4.8 and the Linux std c++ library.
When using test --stdin, std::cin.get() returns -1 when it encounters EOF before it actually sets the EOF status on std::cin, indirectly causing Json::parse() to fail, complaining about "unexpected trailing (-1)".
First I want to thank you @dropbox to share this project.
I'm handling this simple json benchmark project https://github.com/loretoparisi/ios-json-benchmark
Here some results compared to well known parsers (C++, Objective-C so far only) for mobile devices and not like JSONKit
, Gason
, RapidJSON
, Apple's NSJSONSerialization
(more to come). I have integrated Json11
The integration is as simple as
#import "json11.hpp"
@implementation Json11
- (NSString*)parse:(NSString*)json {
const char* data = [json UTF8String];
json11::Json parser;
parser = json11::Json(data);
std::string jsonString;
parser.dump(jsonString);
return [NSString stringWithstring:jsonString];
}
@end
where [NSString stringWithstring:jsonString]
converts a std:string
to a iOS Foundation NSString
5 times parsing of a 322 Bytes JSON file
json11 uses locale-dependent functions for conversion between double and it's string representation. On Ubuntu with Russian language it prints doubles with comma like '3,1415926'. On Windows with Russian language pack or any OS with English language it prints '3.1415926' and parser also expects '3.1415926' so '3,1415926' cannot be parsed.
I began modifying a fork to remove finals etc, but that may contrast greatly with the design/intent (or required utilities like regex). Dig this library cause of its footprint. Sometime soon we'll be migrating towards gcc 4.8 in production
Hi, it is very good, if you library would be header-only.
If you have compile options set to throw a compile error on floating point comparison then there is trouble here:
I don't know a suitable template specialization that works here. That does mean there is not one.
https://github.com/dropbox/json11/blob/master/json11.cpp#L163
This needs an "epsilon" comparison.
https://github.com/dropbox/json11/blob/master/json11.cpp#L176
and on the int templated
https://github.com/dropbox/json11/blob/master/json11.cpp#L185
which is strange but easy to fix with a type cast.
Will submit a PR if I find a good fix for everything.
The copy constructor in json11.h is like this : "const Value & operator[](size_t i) const"
So user can not update an array by "[]", for example : obj["array"][0] = a_json_value;
Why is it designed like this?
So, I got a json and the followign code errors rn because soemthing is either wrong is incorrect and yes this must not create the json ONLY read
from it. The read data should then be loaded up as a array and iterated through.
ifstream ifile;
int fsize;
char * inBuf;
ifile.open("%UserProfile%\\vbtrpdet database temp\\checkwindow.json", NULL);
ifile.seekg(0, ios::end);
fsize = (int)ifile.tellg();
ifile.seekg(0, ios::beg);
inBuf = new char[fsize];
//Error C2440.
ifile.read(inBuf, fsize);
//Error C2440.
string WINDOW_NAMES = (LPCSTR)ifile;
ifile.close();
//Error C2440.
Json my_json = Json::object { { "detectlist", WINDOW_NAMES } };
while(looping == true) {
//Error C2660, C2440
for (auto s : Json::array { Json::object { { "detectlist", Json::array_items(my_json) } } }) {
//Code to do here for each strign in the json array. (Note: that in my code I use this info to call FindWindow
};
};
Hi,
I'm trying to use json11 in c++ code that will be used in iOS and Android. I've no problem to compile json11 in iOS but in Android I've the following error:
"Error variable 'json11::Json json11::final' has initializer but incomplete type"
Seems that in the NDK's c++ is not supported the 'final' keyword. I'm using gradle to build my android app and I've enabled c++11 with -std=c++11 (my cFlags are "-std=c++11 -fno-rtti -fno-exceptions").
Any suggestion to solve the problem?
Is this json11 already used in Android projects with NDK?
Thanks in advance.
Giannandrea
I would like to have [] no const accessor to override existing element.
Also it will be nice to have Json::AddElement to make it possible to add new element into Object/Array
Hi all
Very good library!!
I have question
I want to use the library in different threads (not gonna use the same object on different threads).
Is the library thread safe?
thanks in advance =]
I'm trying to use this json serializer with long ints and unsigned ints and such. When I try to make Json objects using the initialization syntax with these other integer types, I see errors like:
conversion from ‘long int’ to ‘const json11::Json’ is ambiguous
Is there any interest in supporting other integer types? This project uses c++11, so it would be possible to use templates along with the "integral" concept. Maybe the JsonInt class could become a JsonInt class where std::is_integal is true.
If this idea won't work with this code or the maintainers aren't interested, my project will use a version of json11 with a duplicate a lot of code and having a lot of s/Int/Long and such. If the decision of this conversation is not to use a template+concept approach, let me know if I should submit a pull request for a version of this project with extra boilerplate for other integer types.
Is there any way to output a Json string with fixed precision for doubles? for e.g. if I have some json object like:
{"a":0.123435231, "b":1.238431123}
I only want to keep 5 decimal places when outputting it as a string.
{"a":0.12344, "b": 1.23843}
The goal is to put it into a database. We can save lots of spaces by keeping some decimal places.
I have some values of type int
, double
and string
type. Along with them i have one 1-1 std::vector
of 1-D and 2-D respectively.
How to build json object of such types.
I have tried this but i don't why, it didn't work.
Json my_json = Json::object {
{ "key1", intVal },
{ "key2", doubleVal },
{ "key3", "stringVal"},
{ "key4", Json::array (vector1d) }, // Not sure of this part.
{"key5", Json::array (vector2d)}, // Not sure of this part too.
};
It is possibile to avoid the alphabetical sorting of the keys in an object?
I have std::vectorstd::string
each string value is json object = "{"key":"value"}"
How can make a Json::object of value
"[{"key":"value"}, {"key":"value"}]"
This means you could put comments in non-minified JSON, but then dump() it out to produce minified JSON (with no comments).
Hello, I'm new to json11, in previous I using the rapidjson, I want to create below JSONs with json11, must I build the whole JSON string first in order to assign to json11::Json? It's possible have some other ways to do that ?
1:
{"transports":{"1":{"protocol":"TCP","port":5060},
"2":{"protocol":"UDP","port":5062},
"3":{"protocol":"TLS","port":5068}},
2:
{" request ":" clear", "ids":[1, 2, 3]}
3:
{"response":" GetAllocations ",
"ports":[1, 9098, 9099, 2, 9100, 9101, 3, 9102, 9103],
"code": 200"}
With rapidjson, I can do it likes below, does json11 supports similar way ?
writer.String("transports");
writer.StartObject();
int counter = 0;
TransportSet::iterator it = transports.begin();
for (; it != transports.end(); ++it)
{
++counter;
char temp[32] = { 0 };
itoa(counter, temp, 10);
writer.String(temp);
writer.StartObject();
writer.String("protocol");
writer.String(it->protocol.c_str());
writer.String("port");
writer.String(it->transportPort.c_str());
writer.EndObject();
}
writer.EndObject();
Would be nice to have a Json constructor accept the std::unordered_map parameter as an object as well.
I really like the library design and would like to use it cross platform. Unfortunately there are a few roadblocks for using it with MSVC12 (VS2013):
The first one can be easily fixed by removing the initializers and adding them to the initializer-list in statics():
struct Statics {
const std::shared_ptr<JsonValue> null;
const std::shared_ptr<JsonValue> t;
const std::shared_ptr<JsonValue> f;
const string empty_string;
const vector<Json> empty_vector;
const map<string, Json> empty_map;
};
const Statics & statics() {
static const Statics s {
make_shared<JsonNull>(),
make_shared<JsonBoolean>(true),
make_shared<JsonBoolean>(false),
"",
vector<Json>(),
map<string, Json>()
};
return s;
}
The missing noexcept and sprintf are a bit harder. MSVC12 does not (yet) include them. It is possible to create a preprocessor define for noexcept after the STL header includes (as an error is thrown when trying to define the missing noexcept myself). snprintf can be replaced by _snprintf but unfortunately behaves a bit different (snprintf truncates and always 0-terminates, _snprintf does not 0-terminate if the buffer is too small, also the return values are different which are not used anyway).
I didn't invest enough much time digging in c++11s templating features to understand the third problem yet. A simple solution is to comment out the two constructors but I am sure there is a better solution.
This is an issue for me and I don't know if you are interested in supporting MSVC12 (don't know if this gets better with the next compiler update).
PS: Having this library header only would be really nice too, but that's secondary for now
Json data send to post method given below is
{
"user_id":1,
"name": ["Alice","Bob","Peter"]
}
CROW_ROUTE(app,"/saveName")
.methods("POST"_method)
([](const crow::request& req){
string input_error;
auto x= Json::parse(req.body, input_error);
if(x == nullptr)
crow::response(400);
auto userId = x["user_id"].int_value();
std::vector<string> inp;
for(auto& j: x["name"].array_items()) {
inp.push_back(j.dump());
}
});
And it's parsing name in vector
inp as "Alice"
,"Bob"
and "Peter"
but i want to parse it as Alice
,Bob
and Peter
.
It would be nice if there was a way to configure formatting in dump:
hey, i got confused when i read the code about the comment part.first:when the comment is start with "//",why it must end with "/n"? is only one line comment startwith "//" is not allowed? second: for the multi line comment, when the end is "*/" ,why this situation is wrong?
thanks you for your explanation
json11 fails to build with clang 4.0 likely due to llvm-mirror/clang@4b6ad14
% /usr/bin/clang -v
FreeBSD clang version 4.0.0 (branches/release_40 292009) (based on LLVM 4.0.0)
Target: x86_64-unknown-freebsd12.0
Thread model: posix
InstalledDir: /usr/bin
ext/json11/json11.cpp:153:24: error: invalid operands to binary expression
('nullptr_t' and 'nullptr_t')
return m_value < static_cast<const Value<tag, T> *>(other)->m_value;
~~~~~~~ ^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ext/json11/json11.cpp:209:5: note: in instantiation of member function
'json11::Value<json11::Json::Type::NUL, nullptr_t>::less' requested here
JsonNull() : Value(nullptr) {}
^
Also reported here: PowerDNS/pdns#4913
This is the current repository version for Ubuntu 12 Server LTS. It currently doesn't compile. Nice library design, though. Very impressed with the API!
I found Json(o).dump() extremely useful for debugging.
Unfortunately I'm finding that it now crashes XCode 7 and 8. Anyone getting similar problems ?
J
I use json.dump()
for my result. And I got a problem, when I put double in the object. I got 150.00700000000001
when the double value is 150.0
. How can I solve this problem? Thanks
I haven't measured, but I'm pretty sure that this would yield improvements in performance and memory consumption, and should be fairly trivial to implement. I am happy to create a pull request, if that's welcome.
json.org specifies a "A string is a sequence of zero or more Unicode characters" I have always taken that to mean utf8. parse_string() does not seem to handle multi byte utf8. I will be happy to do the work and provide a pull request, If its agreed that utf8 support is desirable.
This problem actually surfaced with gcc 6 when trying to create a copy of std::experimental::optional<json11::Json>
, but I believe these two lines simulate the underlying issue even with earlier gcc versions:
std::experimental::optional<json11::Json> foo;
json11::Json foo2 = foo;
The compilation fails with:
error: 'const class std::experimental::fundamentals_v1::optional<json11::Json>' has no member named 'begin'
Json(const V & v) : Json(array(v.begin(), v.end())) {}
I think the correct error would be that there is no matching operator=
. The enable_if
condition for vector-like objects is too loose, because optionals also have a member type value_type
.
A quickfix (checking for presence of a begin()
function) seems to solve the issue.
It would be nice to have some example code how to read out and parse a file.
When using AppleClang 7.3 to build a project that has a dependency on json11 and contains a C file, the build errors out with:
error: invalid argument '-std=c++11' not allowed with 'C/ObjC'
..due to the hardcoded compile flag added in target_compile_options
This can be fixed by making use of CXX_STANDARD
, which will allow cmake to add the correct c++11 flag only to appropriate files (PR incoming..)
Minimal reproduction example below:
build ▹ cat ../CMakeLists.txt
cmake_minimum_required(VERSION 3.2)
add_subdirectory(../json11 lib)
add_executable(test_prog test.c)
target_link_libraries(test_prog json11)
build ▹ cmake ..
-- The C compiler identification is AppleClang 7.3.0.7030031
-- The CXX compiler identification is AppleClang 7.3.0.7030031
-- Check for working C compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc
-- Check for working C compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++
-- Check for working CXX compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Configuring done
-- Generating done
-- Build files have been written to: /Users/adam/workspace/test_with_json11/build
build ▹ make
Scanning dependencies of target json11
[ 16%] Building CXX object lib/CMakeFiles/json11.dir/json11.cpp.o
[ 33%] Linking CXX static library libjson11.a
[ 33%] Built target json11
Scanning dependencies of target test_prog
[ 50%] Building C object CMakeFiles/test_prog.dir/test.c.o
error: invalid argument '-std=c++11' not allowed with 'C/ObjC'
make[2]: *** [CMakeFiles/test_prog.dir/test.c.o] Error 1
make[1]: *** [CMakeFiles/test_prog.dir/all] Error 2
make: *** [all] Error 2
build ▹
json11 cannot parse expressions like True
, NULL
, etc.
Json::m_ptr
looks like std::unique_ptr
would be more suited? I didn't see any sharing that suggests shared_ptr
is needed, but only eye-balled it.
Hi, it's possible has such method ?
if (json["k1"].exists())
{
// do sth
}
Here is the sample response of one of my apis. And I would like to parse it using json11
.
{
"status": 1,
"message": {
"fundNames": [
"SBI Premier Liquid Fund - Institutional - Growth",
"SBI Premier Liquid Fund - Institutional - Growth"
],
"fundNavs": [
[
{
"date": "2017-02-22",
"nav": 2552.4454
},
{
"date": "2017-02-21",
"nav": 2551.9707
}
],
[
{
"date": "2017-02-22",
"nav": 2552.4454
},
{
"date": "2017-02-21",
"nav": 2551.9707
},
{
"date": "2017-02-18",
"nav": 2550.6512
}
]
]
}
}
Here is my try
string inputError;
auto y = Json::parse(r.text, inputError);
auto status = y["status"].int_value();
if (status == 1) {
for (auto &k: y["message"].array_items()) {
map<string, double> data;
for (auto &m : k[fundNavs].array_items()) {
auto nav = m["nav"].number_value();
auto nDate = m["date"].string_value();
data[nDate] = nav;
}
}
}
When using json11 with the android ndk r10b, the resulting dynamic library is not loadable because of a missing atof symbol. I fixed the problem here using strtod instead of atof. I don't know if the issue should be fixed here or in the ndk.
Is it possible to add entries to an existing Json::object
and use it like a Python dictionary?
Json data = Json::object {};
data["this"] = 42; // doesn't work
// or maybe data.append or some other way to do it?
If it's not possible at the moment ... is it possible to add this feature?
Why there are no operator int()
, operator std::string()
, operator bool()
and others in Json
class?
Hi
Thanks for this library! I do find the 'user guide' rather sparse however. I can't figure out how to add a key:value pair to a json object that already exists. Say I have :
JSON j = JSON::object{
{ "key1", "value1" },
{ "key2", false },
{ "key3", JSON::array { 1, 2, 3 } },
{ "key4", 666.333 },
{ "key5", JSON::array { 1, 2, JSON::object{ { "key1", "value1" },
{ "key6", false } } } }
};
Now I want to add another key:value pair like :
j.add("key", "value"); //no add() member!
How would I do this?
furthermore, how do I change an existing value?
j["key5"] = "something else";
Any way of doing this?
Many thanks, Peter
json11 raises a "pure virtual function call" exception when trying to dump the following json:
{"params": {}, "method": "ping", "id": 1}
this only happens in gdb
How about adding an logical operator bool Json::operator! () const { return is_null(); }
?
I'd like to use syntax like this:
json11::Json obj = json11::Json::parse(myJsonStr, errorStr);
if (!obj["MyKey"])
return false;
Issue for tracking a long-standing issue which was never tracked publicly before. It's natural to want to construct a nested JSON array as follows:
Json nested_array = Json::array { Json::array { 1, 2, 3 } };
This used to work as expected, until a language standard change DR1467 which caused the array constructor to be interpreted as a move instead of creating a nested array from an initializer_list. This is only an issue for single-element arrays, since 2 elements would break the ambiguity and be interpreted as an initializer_list.
Most new compilers have the new dangerous behavior now. There's a "canary" in the unit test which is meant to point out whether your compiler has the bad behavior: https://github.com/dropbox/json11/blob/master/test.cpp#L195
There is a new issue being tracked by the standards committee on this, but I haven't seen any action. Latest status is here: http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#2137
Meanwhile the best workaround is to build these nested arrays in multiple steps using push_back()
I would like to parse this json
object.
{
"status": 1,
"message": [
{
"name": "UTI Dual Advantage Fixed Term Fund Series I-IV (1099 Days) - Direct Plan - Dividend Option",
"uploadDate": "2015-08-18",
"value": 10.3842
},
{
"name": "UTI Dual Advantage Fixed Term Fund Series I-IV (1099 Days) - Direct Plan - Dividend Option",
"uploadDate": "2015-08-18",
"value": 10.3842
},
{
"name": "UTI Dual Advantage Fixed Term Fund Series I-IV (1099 Days) - Direct Plan - Dividend Option",
"uploadDate": "2015-08-18",
"value": 10.3842
}]
}
Here is my try.
string input_error;
auto y = Json::parse(r1.text,input_error);
auto status = y["status"].int_value();
for(auto& i: y["message"].arry_items()) {
// Now i don't know, what to do.
}
First of all, congrats on this great little library! I've been looking for a lightweight modern implementation for a while now, really happy to finally have found it.
The only thing that I was a bit irritated by was that there isn't any support for int64 and uint32 / 64 types.
Json doesn't make that distinction, but if you want a non-float value that is larger than 32 bits, or an unsigned int without loosing the values from 1 << 15 and beyond, then you currently have to go through double, which seems odd.
The simple solution could be to internally store all such values as long (in a new JsonLong class), not int, and then do the casting in int_value(), long_value() uint_value() (or unsigned_int_value() if you like it verbose), ulong_value(), ...) But I guess this would still cause troubles when exporting, as it will have to be known if a value was signed or unsigned.
I'm using a different string class than std::string.
It would be good to add this either as a #define or a template parameter which defaults to std::string.
If so, is this something which you would accept into the code base?
Then, which method would you prefer?
If it would be a define, it should be something like:
#ifndef JSON11_STRING_TYPE
#define JSON11_STRING_TYPE std::string
#endif
I have a domain-specific vector class as well, which might be useful to tweak as well...
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.