I am trying to get the array from my JSON Stinrg defined in the main function. I have used libjson API for this, simple key value is easy to get so I am able to get the value of RootA but how about this array in ChildA. Please let me know
#include <iostream>
#include <libjson/libjson.h>
#include <stdio.h>
#include <string.h>
using namespace std;
char rootA[20];
int childB;
int *childInt;
void ParseJSON(JSONNODE *n) {
if (n == NULL) {
printf("Invalid JSON Node\n");
return;
}
JSONNODE_ITERATOR i = json_begin(n);
while (i != json_end(n)) {
if (*i == NULL) {
printf("Invalid JSON Node\n");
return;
}
// recursively call ourselves to dig deeper into the tree
if (json_type(*i) == JSON_ARRAY || json_type(*i) == JSON_NODE) {
ParseJSON(*i);
}
// get the node name and value as a string
json_char *node_name = json_name(*i);
// find out where to store the values
if (strcmp(node_name, "RootA") == 0) {
json_char *node_value = json_as_string(*i);
strcpy(rootA, node_value);
cout << rootA<<"\n";
json_free(node_value);
} else if (strcmp(node_name, "ChildA") == 0) {
JSONNODE *node_value = json_as_array(*i);
childInt=reinterpret_cast<int *>(&node_value);
cout << childInt[0]<<"\n";
cout << childInt[1]<<"\n";
json_free(node_value);
} else if (strcmp(node_name, "ChildB") == 0) {
childB = json_as_int(*i);
cout << childB;
}
// cleanup and increment the iterator
json_free(node_name);
++i;
}
}
int main(int argc, char **argv) {
char
*json =
"{\"RootA\":\"Value in parent node\",\"ChildNode\":{\"ChildA\":[1,2],\"ChildB\":42}}";
JSONNODE *n = json_parse(json);
ParseJSON(n);
json_delete(n);
return 0;
}
Thanks not-sehe but I got the solution for this
Ok I got it... treat array as a node and iterate over it again as if its a value with blank key. You can see the code part which did it..
if (json_type(*i) == JSON_ARRAY) {
cout << "\n Its a Json Array";
JSONNODE *arrayValue = json_as_array(*i);
JSONNODE_ITERATOR i1 = json_begin(arrayValue);
while (i1 != json_end(arrayValue)) {
cout << "\n In Array Loop ";
cout << json_as_int(*i1);
++i1;
}
}
This is probably not the answer you were looking for, but let me just demonstrate that a library with a slightly more modern interface makes this a lot easier (test.cpp):
#include <sstream>
#include "JSON.hpp"
int main()
{
auto document = JSON::readFrom(std::istringstream(
"{\"RootA\":\"Value in parent node\",\"ChildNode\":{\"ChildA\":[1,2],\"ChildB\":42}}"));
auto childA = as_object(
as_object(document)[L"ChildNode"]
)[L"ChildA"];
std::cout << childA << std::endl;
}
Which prints
[1,2]
It's using my own minimalist implementation of the rfc4627 specs. It's minimalist in interface only, supporting the full syntax and UNICODE.
The API interface is quite limited, but you can already see that working without C-style pointers, with proper dictionary lookups, key comparisons etc. makes it a less tedious and error prone:
// or use each value
for(auto& value : as_array(childA).values)
std::cout << value << std::endl;
// more advanced:
JSON::Value expected = JSON::Object {
{ L"RootA", L"Value in parent node" },
{ L"ChildNode", JSON::Object {
{ L"ChildA", JSON::Array { 1,2 } },
{ L"ChildB", 42 },
} },
};
std::cout << "Check equality: " << std::boolalpha << (document == expected) << std::endl;
std::cout << "Serialized: " << document;
See the full parser implementation (note: it includes serialization too) at github: https://github.com/sehe/spirit-v2-json/tree/q17064905
Related
I'm trying to use my own list with a class called "NameCard" which has two variables, name and phone.
However, complier crushed when I use LFirst(LData pData).
It worked with simple int type list.
any feedback would be greatly appreciated
Here is my code.
Class name: ArrayList.cpp
int ArrayList::LFirst(LData* pData)
{
if (numOfData == 0)
return 0;
curPosition = 0;
*pData = arr[0];
return 1;
}
Class name: NameCard.cpp
NameCard::NameCard()
{
}
NameCard::NameCard(const char* iName, const char* iPhone)
{
strcpy_s(name, iName);
strcpy_s(phone, iPhone);
}
void NameCard::ShowNameCardInfo()
{
std::cout << "Name: " << name << ", phone: " << phone << std::endl;
}
int NameCard::NameCompare(char* iName)
{
return strcmp(name, iName);
}
void NameCard::ChangePhoneNum(char* iPhone)
{
strcpy_s(phone, iPhone);
}
Class name: NameCardImplementation.cpp
#include <iostream>
#include "ArrayList.h"
#include "NameCard.h"
int main()
{
ArrayList list;
NameCard *pData(NULL);
NameCard nc1("Alice", "010-1111-2222");
NameCard nc2("Brandon", "010-2222-3333");
NameCard nc3("Jack", "010-3333-4444");
list.LInsert(nc1);
list.LInsert(nc2);
list.LInsert(nc3);
//nc1.ShowNameCardInfo();
//list.arr[0].ShowNameCardInfo();
//std::cout << list.LCount() << std::endl;
int a = list.LFirst(pData);
std::cout << a << std::endl;
//if (list.LFirst(pData))
//{
// pData->ShowNameCardInfo();
//}
}
Crash is due to null pointer access in ArrayList::LFirst.
From the limited code you have pasted, I see that there is no memory created for pData.
NameCard *pData(NULL);
Are you attaching the memory for pData anywhere else in your code?
I need to find all the keys in the kTypeNames[] with rapidJSON library.
Trying to iterate all the nodes but I'm missing something; here's the code:
#include <iostream>
#include <fstream>
#include <string>
#include <bits/stdc++.h>
#include <unistd.h>
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
using namespace rapidjson;
using namespace std;
const char* kTypeNames[] = { "id", "text", "templ_text", "key" };
int main(int argc, char* argv[]) {
string line;
char json[65000];
std::ifstream file(argv[1]);
unsigned long i = 0;
if (file.is_open()) {
while (!file.eof()) {
file.get(json[i]);
i++;
}
file.close();
} else {
cout << "Unable to open file";
}
Document document;
document.Parse(json);
printf("\n\n\n\n*********Access values in document**********\n");
assert(document.IsObject());
for (auto Typename : kTypeNames) {
if (document.HasMember(Typename)) {
cout << "\n";
cout << Typename << ":" << document[Typename].GetString()<< endl;
cout << "\n";
}
else {
cout << "\n None\n";
}
}
It does not works with a nested JSON.
{
"node": {
"text": "find this",
"templ_text": "don't find",
"ver": "don't find"
},
"ic": "",
"text": "also this",
"templ_text": "don't care",
"par": {
"SET": {
"vis": "<blabla>",
"text": "keyFound",
"templ_text": "don't need this"
}
}
}
This is the output:
None
text:also this
templ_text:don't care
None
I would like to find all the "text" keys
How can I iterate through all the nodes/ json document?
The code you have is just searching for a list of pre-defined keys directly within the document root (document.HasMember is not a recursive search!).
You could just loop through the document nodes recursively. For example for object/map nodes, you loop on the MemberBegin() and MemberEnd() iterators, similar to a std::map or other standard containers.
for (auto i = node.MemberBegin(); i != node.MemberEnd(); ++i)
{
std::cout << "key: " << i->name.GetString() << std::endl;
WalkNodes(i->value);
}
Array uses Begin() and End(). Then, when you encounter a node with a "text" member, you can output the value of that node (i->value).
Alternatively, rather than using a Document DOM object, you can do it with the parser stream. Rapidjson uses a "push" API for this, where it calls methods you define in a class as it encounters each piece of JSON. Specifically, it will call a Key method.
class MyHandler : public BaseReaderHandler<UTF8<>, MyReader> {
bool Key(const char* str, SizeType length, bool copy)
{
std::cout << "Key: " << str << std::endl;
}
...
};
MyHandler handler;
rapidjson::Reader reader;
rapidjson::StringStream ss(json);
reader.Parse(ss, handler);
This gets a bit more complex, you will want to set a flag of some sorts, and then output the next value callback after.
class MyHandler : public BaseReaderHandler<UTF8<>, MyReader> {
bool Key(const char* str, SizeType length, bool copy)
{
isTextKey = strcmp(str, "text") == 0; // Also need to set to false in some other places
return true;
}
bool String(const char* str, SizeType length, bool copy)
{
if (isTextKey) std::cout << "text string " << str << std::endl;
return true;
}
...
bool isTextKey = false;
};
Also remember, that JSON allows a null within a string \0, which is why also have the size parameters and members, as well as Unicode. So to fully support any JSON document that needs accounting for.
I am playing with c++ code today. Learning about std containers. I'm trying to insert and update data in a std::map but for some reason I can't insert values into a map. Keys will insert but not values. The code at the bottom will print the following if you enter something into the terminal that opens. In this example I entered "test". Anyway, my questions are, why is the insert returning false, why in the value not inserting?
test
first
failed
Context1 :
Here is the code:
#include "stdafx.h"
#include <string>
#include <iostream>
#include <map>
#include <random>
static std::map<std::string, std::string> currentFullState;
static const std::string sDEFAULT_STRING = "";
void PringCurrentState()
{
std::map<std::string, std::string>::iterator stateData = currentFullState.begin();
while (stateData != currentFullState.end())
{
std::cout << stateData->first << " : ";
std::cout << stateData->second << std::endl;
stateData++;
};
}
void UpdateState(std::string context, std::string data)
{
if (currentFullState[context] == sDEFAULT_STRING)
{
// first entry, possibly special?
std::cout << "first" << std::endl;
auto result = currentFullState.insert(std::make_pair(context, data.c_str()));
if (result.second == false)
std::cout << "failed" << std::endl;
else
std::cout << "good" << std::endl;
}
else if (data != currentFullState[context])
{
// change in value
}
else
{
currentFullState[context] == data;
}
}
void DoWork()
{
if (rand() % 2)
{
UpdateState("Context1", "Data1");
}
else
{
UpdateState("Context2", "Data2");
}
}
int main()
{
std::string command = "";
for (;;)
{
PringCurrentState();
std::cin >> command;
DoWork();
if (command == "q")
{
break;
}
}
return 0;
}
Why does the insert not work?
Certainly would help if you wrote
currentFullState[context] = data;
instead of
currentFullState[context] == data;
Also
auto result = currentFullState.insert(std::make_pair(context, data));
should be preferred to
auto result = currentFullState.insert(std::make_pair(context, data.c_str()));
Slightly surprised that the second one compiles.
=========================================================================
The real reason the insert fails is that you are adding that key for the second time. This is the first time
if (currentFullState[context] == sDEFAULT_STRING)
operator[] on a map always adds the key to the map. This is why your second attempt to add with
auto result = currentFullState.insert(std::make_pair(context, data.c_str()));
fails, the key is already present. If you had written
currentFullState[context] = data;
Then it would work.
I'm using LLVM api in order to parse bitcode files. I have the following snippet and I'm using this command to generate the bitcode $CC -emit-llvm -c -g source.c where CC is set to the clang path.
#include <stdio.h>
struct Point {
int a;
int b;
};
int func_0(struct Point p, int x) {
return 0;
}
The TypeID is supposed to have a numeric value, based on the type of the parameter. However, both for the integer x and the struct Point I obtain the value of 10 which is referred as a TokenTyID. So, I decided to use the functions isIntegerTy() and isStructTy(), respectively, to see if at least in this case, I obtain the right result. This solution works for the integer parameter x, but not for the struct. How can I correctly identify structs and read their fields?
Just to completeness, to parse the bitcode I use this code:
using namespace llvm;
int main(int argc, char** argv) {
LLVMContext context;
OwningPtr<MemoryBuffer> mb;
MemoryBuffer::getFile(FileName, mb);
Module *m = ParseBitcodeFile(mb.get(), context);
for (Module::const_iterator i = m->getFunctionList().begin(), e = m->getFunctionList().end(); i != e; ++i) {
if (i->isDeclaration() || i->getName().str() == "main")
continue;
std::cout << i->getName().str() << std::endl;
Type* ret_type = i->getReturnType();
std::cout << "\t(ret) " << ret_type->getTypeID() << std::endl;
Function::const_arg_iterator ai;
Function::const_arg_iterator ae;
for (ai = i->arg_begin(), ae = i->arg_end(); ai != ae; ++ai) {
Type* t = ai->getType();
std::cout << "\t" << ai->getName().str() << " " << t->getTypeID()
<< "(" << t->getFunctionNumParams() << ")"
<< " is struct? " << (t->isStructTy() ? "Y" : "N")
<< " is int? " << (t->isIntegerTy() ? "Y" : "N")
<< "\n";
}
}
return 0;
}
I read this post Why does Clang coerce struct parameters to ints about the translation performed by clang with the structs and I'm pretty sure that is my same problem.
Since clang changes the function signature in the IR, you will have to get that information using debug info. Here is some rough code:
DITypeIdentifierMap TypeIdentifierMap;
DIType* getLowestDINode(DIType* Ty) {
if (Ty->getTag() == dwarf::DW_TAG_pointer_type ||
Ty->getTag() == dwarf::DW_TAG_member) {
DIType *baseTy =
dyn_cast<DIDerivedType>(Ty)->getBaseType().resolve(TypeIdentifierMap);
if (!baseTy) {
errs() << "Type : NULL - Nothing more to do\n";
return NULL;
}
//Skip all the DINodes with DW_TAG_typedef tag
while ((baseTy->getTag() == dwarf::DW_TAG_typedef || baseTy->getTag() == dwarf::DW_TAG_const_type
|| baseTy->getTag() == dwarf::DW_TAG_pointer_type)) {
if (DITypeRef temp = dyn_cast<DIDerivedType>(baseTy)->getBaseType())
baseTy = temp.resolve(TypeIdentifierMap);
else
break;
}
return baseTy;
}
return Ty;
}
int main(int argc, char** argv) {
LLVMContext context;
OwningPtr<MemoryBuffer> mb;
MemoryBuffer::getFile(FileName, mb);
Module *m = ParseBitcodeFile(mb.get(), context);
if (NamedMDNode *CU_Nodes = m.getNamedMetadata("llvm.dbg.cu")) {
TypeIdentifierMap = generateDITypeIdentifierMap(CU_Nodes);
}
SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
F.getAllMetadata(MDs);
for (auto &MD : MDs) {
if (MDNode *N = MD.second) {
if (auto *subRoutine = dyn_cast<DISubprogram>(N)->getType()) {
if (!subRoutine->getTypeArray()[0]) {
errs() << "return type \"void\" for Function : " << F.getName().str()
<< "\n";
}
const auto &TypeRef = subRoutine->getTypeArray();
for (int i=0; i<TypeRef.size(); i++) {
// Resolve the type
DIType *Ty = ArgTypeRef.resolve(TypeIdentifierMap);
DIType* baseTy = getLowestDINode(Ty);
if (!baseTy)
return;
// If that pointer is a struct
if (baseTy->getTag() == dwarf::DW_TAG_structure_type) {
std::cout << "structure type name: " << baseTy->getName().str() << std::endl();
}
}
}
}
}
}
I know it looks ugly but using debug info is not easy.
I am know approaching to boost property tree and saw that it is a good feature of boost libs for c++ programming.
Well, I have one doubt? how to iterate a property tree using iterators or similar?
In reference there is just an example of browsing the tree through:
BOOST_FOREACH
But is there nothing more? Something like an stl-like container? It would be a better solution, speaking about code quality....
Here is what I came up with after much experimentation. I wanted to share it in the community because I couldn't find what I wanted. Everybody seemed to just post the answer from the boost docs, which I found to be insufficient. Anyhow:
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <string>
#include <iostream>
using namespace std;
using boost::property_tree::ptree;
string indent(int level) {
string s;
for (int i=0; i<level; i++) s += " ";
return s;
}
void printTree (ptree &pt, int level) {
if (pt.empty()) {
cerr << "\""<< pt.data()<< "\"";
}
else {
if (level) cerr << endl;
cerr << indent(level) << "{" << endl;
for (ptree::iterator pos = pt.begin(); pos != pt.end();) {
cerr << indent(level+1) << "\"" << pos->first << "\": ";
printTree(pos->second, level + 1);
++pos;
if (pos != pt.end()) {
cerr << ",";
}
cerr << endl;
}
cerr << indent(level) << " }";
}
return;
}
int main(int, char*[]) {
// first, make a json file:
string tagfile = "testing2.pt";
ptree pt1;
pt1.put("object1.type","ASCII");
pt1.put("object2.type","INT64");
pt1.put("object3.type","DOUBLE");
pt1.put("object1.value","one");
pt1.put("object2.value","2");
pt1.put("object3.value","3.0");
write_json(tagfile, pt1);
ptree pt;
bool success = true;
try {
read_json(tagfile, pt);
printTree(pt, 0);
cerr << endl;
}catch(const json_parser_error &jpe){
//do error handling
success = false
}
return success;
}
Here is the output:
rcook#rzbeast (blockbuster): a.out
{
"object1":
{
"type": "ASCII",
"value": "one"
},
"object2":
{
"type": "INT64",
"value": "2"
},
"object3":
{
"type": "DOUBLE",
"value": "3.0"
}
}
rcook#rzbeast (blockbuster): cat testing2.pt
{
"object1":
{
"type": "ASCII",
"value": "one"
},
"object2":
{
"type": "INT64",
"value": "2"
},
"object3":
{
"type": "DOUBLE",
"value": "3.0"
}
}
BOOST_FOREACH is just a convenient way for iterating that can be done by iterator, begin() and end()
Your_tree_type::const_iterator end = tree.end();
for (your_tree_type::const_iterator it = tree.begin(); it != end; ++it)
...
And since C++11 it's:
for (auto& it: tree)
...
I ran into this issue recently and found the answers incomplete for my need, so I came up with this short and sweet snippet:
using boost::property_tree::ptree;
void parse_tree(const ptree& pt, std::string key)
{
std::string nkey;
if (!key.empty())
{
// The full-key/value pair for this node is
// key / pt.data()
// So do with it what you need
nkey = key + "."; // More work is involved if you use a different path separator
}
ptree::const_iterator end = pt.end();
for (ptree::const_iterator it = pt.begin(); it != end; ++it)
{
parse_tree(it->second, nkey + it->first);
}
}
Important to note is that any node, except the root node can contain data as well as child nodes. The if (!key.empty()) bit will get the data for all but the root node, we can also start building the path for the looping of the node's children if any.
You'd start the parsing by calling parse_tree(root_node, "") and of course you need to do something inside this function to make it worth doing.
If you are doing some parsing where you don't need the FULL path, simply remove the nkey variable and it's operations, and just pass it->first to the recursive function.
An addition to the answer How to iterate a boost property tree? :
In the C++11 style range based for for (auto node : tree), each node is a std::pair<key_type, property_tree>
Whereas in the manually written iteration
Your_tree_type::const_iterator end = tree.end();
for (your_tree_type::const_iterator it = tree.begin(); it != end; ++it)
...
the iterator it is a pointer to such a pair. It's a tiny difference in usage. For example, to access the key, one would write it->first but node.first.
Posted as a new answer, because my proposed edit to the original answer was rejected with the suggestion to post a new answer.
BFS based print ptree traversal, May be used if we want to do some algorithmic manipulation
int print_ptree_bfs(ptree &tree) {
try {
std::queue<ptree*> treeQ;
std::queue<string> strQ;
ptree* temp;
if (tree.empty())
cout << "\"" << tree.data() << "\"";
treeQ.push(&tree);
//cout << tree.data();
strQ.push(tree.data());
while (!treeQ.empty()) {
temp = treeQ.front();
treeQ.pop();
if (temp == NULL) {
cout << "Some thing is wrong" << std::endl;
break;
}
cout << "----- " << strQ.front() << "----- " << std::endl;
strQ.pop();
for (auto itr = temp->begin(); itr != temp->end(); itr++) {
if (!itr->second.empty()) {
//cout << itr->first << std::endl;
treeQ.push(&itr->second);
strQ.push(itr->first);
} else {
cout<<itr->first << " " << itr->second.data() << std::endl;
}
}
cout << std::endl;
}
} catch (std::exception const& ex) {
cout << ex.what() << std::endl;
}
return EXIT_SUCCESS;
}