I am creating a JSON file able to read measured value. I have the following structure:
{ "object":
{"object name 1":
{"type":
{"type name":
{"properties":[
{"measure1": 10,
"measure2":5
}
}
}
},
{"object name 2":
{"type":
{"type name":
{"properties":[
{"measure1": 10,
"measure2":5
}
}
}
}
}
}
now object 1 and 2 are exactly the same but they have different name. Is there a possibility of merging these two objects and provide a list of names?
I tried the following without success:
{ "object":
{["object name 1","object name 1"]:
{"type":
I am using C++ to read the file as follows:
std::string s =this->filename;
std::ifstream json_file_stream(s);
if(!json_file_stream)
error("Could not open Json file!");
nlohmann::json radionuclide_json;
json_file_stream >> radionuclide_json;
the code crashes at the last line
Related
I am using the jsoncons library and Visual Studio 2022.
I have a JSON array of objects, which is parsed out of a csv file and stored in 'ojson' object.
For e.g.-
[
{
"author": "Nigel Rees",
"isbn": "0048080489",
"price": 9.95,
"title": "Sayings of the Century"
},
{
"author": "Evelyn Waugh",
"isbn": "0141193557",
"price": 12.99,
"title": "Sword of Honour"
},
{
"author": "Herman Melville",
"isbn": "0553213113",
"price": 10.0,
"title": "Moby Dick"
}
]
I have to save it as a value (in a key:value pair) into another JSON object at any key.
For e.g.-
{
"books": [ < Array of objects > ]
}
This is example of my code-
#include <iostream>
#include <fstream>
#include <jsoncons/json.hpp>
#include <jsoncons_ext/csv/csv.hpp>
using namespace std;
using namespace jsoncons;
using namespace jsoncons::csv;
int main()
{
string path;
ifstream file;
ofstream outFile;
file.open(path); //assume path is a path to local csv file
csv::csv_options options;
options.assume_header(true);
ojson data = csv::decode_csv<ojson>(file, options); //creating ojson object or array
json jsonData; //creating json object
jsonData["books"] = data; //trying to save ojson object at a key "books"
}
But the last part is giving build error.
I have tried different ways of saving values inside a json object as given in jsoncons documentation.
jsonData.insert_or_assign("books",data);
jsonData.insert("books",data);
But all of them are giving build errors.
How to loop through a JSON object in Django template?
JSON:
"data": {
"node-A": {
"test1A": "val1A",
"test2A": "val2A",
"progress": {
"conf": "conf123A"
"loc": "loc123A"
},
"test3A": "val3A"
},
"node-B": {
"test1B": "val1B",
"test2B": "val2B",
"progress": {
"conf": "conf123B"
"loc": "loc123B"
},
"test3B": "val3B"
}
}
I am having trouble accessing the nested values "conf" and "lock" inside "progress". How can I access them in Django template if the data is passed as context i.e. return (request, 'monitor.html', {"data_context": json_data['data']})?
they way you have it set up, your data is in a dictionary called 'data_context'. To access what you need in the template it would be {{data_context.test1A}}.
to not have to use 'data_context.' try this instead,
return (request, 'monitor.html', json_data['data'].to_dict())
Dictionary lookup, attribute lookup and list-index lookups are implemented with a dot notation:
{{ my_dict.key.key_nested }}
As the JSON format behaves like a dictionary in Python, the data stored with the specified keys conf and loc should be accessible with the python notation for dictionaries. Since the provided JSON can be seen as a nested dictionary, you need to "concat" the keys respectively to get your desired data.
Your return statement returns a dictionary which I will call ret so the structure should be:
{"data_context": {
"node-A": {
"test1": "val1A",
"test2": "val2A",
"progress": {
"conf": "conf123A",
"loc": "loc123A"
},
"test3": "val3A"
},
"node-B": {
"test1B": "val1B",
"test2B": "val2B",
"progress": {
"conf": "conf123B",
"loc": "loc123B"
},
"test3": "val3B"
}
}
}
Therefor to access conf and loc:
ret["data_context"]["node-A"]["progress"]["conf"]
will get you the value stored at conf in node-A
Good day. In my QT aplication, there is a need to store the value of structures of the same type in a JSON dictionary.
Values should be possible to add, read, change, delete. I know about the JSON Save Game Example article, I tried to figure it out for a long time, I didn’t come to anything, I also surfed the forums with the same result.
The main problem is this:
Let's say I have the following structure:
struct Laptop{
std::string name;
int price;
int year;
};
And I want to store an array of such structures in a JSON dictionary. I am using the following code:
//filling structure
Laptop Ltemp = {"some name" , 1000, 2022};
//adding structure to JSON object
QJsonObject g;
g.insert("name", Ltemp.name.c_str());
g.insert("price", Ltemp.price);
g.insert("year", Gtemp.year);
//open and wtritingmy JSON
QFile file("path/to/myfile.json");
QByteArray jsonData = file.readAll();
QJsonDocument document = QJsonDocument::fromJson(jsonData);
QJsonObject object = document.object();
QJsonValue value = object.value("mydata");
QJsonArray myArray= value.toArray();
myArray.removeAt(0);
myArray.append(g);
object.insert("mydata", myArray);
document.setObject(object);
//write to file
file.write(document.toJson());
file.close();
{
Expecting at the same time that when you re-apply the code, the data of the structure will be added to the same array, the key of which is "mydata", but in the end I have this:
"mydata": [
{
"name": "some name",
"price": 1000,
"year": 2022
}
],
"mydata": [
{
"name": "some name",
"price": 1000,
"year": 2022
}
]
}
instead of
"mydata": [
{
"name": "some name",
"price": 1000,
"year": 2022
},
{
"name": "some name",
"price": 1000,
"year": 2022
}
]
This question already has an answer here:
How to use boost::property_tree to parse JSON with array root
(1 answer)
Closed 2 years ago.
I am using c++ code to read json string to retrieve value based on specific key names. Example of my json response from web API is in array format like below.
[
{
"username": "123456",
"useraddress": "abc",
"data": [
{
"schedule": true,
"task": "abc",
"risk": "1",
}
],
"date": "0000-00-00"
}
]
Like the above format is the actual response. I have to retrieve date value using key "date".
My code snippet:
{
std::stringstream jsonString;
boost::property_tree::ptree pt;
jsonString << ws2s(Info).c_str();
boost::property_tree::read_json(jsonString, pt);
std::string date = pt.get<std::string>("date");
}
'Info' in above snippet is wsstring containing json response data.
I can able to retrieve "date" if [] square brackets are removed manually. Since it is array format, if I pass without removing brackets, read_json throws error.
Can somebody help this out?
Yeah. Boost Property Tree is a property tree library, not JSON.
You're in luck though, Boost has a JSON library now https://www.boost.org/doc/libs/1_75_0/libs/json/doc/html/index.html
Note: your input isn't valid JSON either, because JSON doesn't strictly allow trailing commas. You can enable them with an option in Boost JSON though:
Live On Compiler Explorer
#include <boost/json.hpp>
#include <iostream>
int main() {
std::string input = R"(
[
{
"username": "123456",
"useraddress": "abc",
"data": [
{
"schedule": true,
"task": "abc",
"risk": "1",
}
],
"date": "0000-00-00"
}
])";
boost::json::parse_options options;
options.allow_trailing_commas = true;
auto json = boost::json::parse(input, {}, options);
for (auto& el : json.as_array()) {
std::cout << el.at("date") << "\n";
}
}
Prints
"0000-00-00"
I have the following code which should read the contents of a text file and parse it as JSON
try {
string_t importFile = argv[++iArgCounter]; // extract filename
ifstream_t f(importFile); // filestream of working file
stringstream_t s; // string stream for holding JSON read from file
json::value v; // JSON read from input file
iArgCounter++; // increment arg counter
if (f) {
s << f.rdbuf(); // stream results of reading from file stream into string stream
f.close(); // close the filestream
v.parse(s); // parse the resultant string stream.
}
}
catch (web::json::json_exception excep) {
std::cout << "ERROR Parsing JSON: ";
std::cout << excep.what();
break;
}
And the following test JSON file
[
{
"Destinations":
[
{
"Domain": "127.0.0.1",
"Name": "GoogleLogin",
"Port": "8090"
}
],
"Listeners":
[
{
"Domain": "127.0.0.1",
"Name": "LoginRequest",
"Port": "8080",
"Route": "ProcessLoginRequest"
}
],
"Name": "LoginProcess",
"Routes":
[
{
"Name": "ProcessLoginRequest",
"Rules":
[{
"DestinationIfTrue": "GoogleLogin",
"LeftTerm":
{
"RuleTermType": 1,
"Value": "NETWORK"
},
"Operator": 2,
"RightTerm":
{
"RuleTermType": 0,
"Value": "NETWORK"
}
}],
"Transformations": []
}
]
}
]
The trouble is no matter what the JSON code I get the error 'Line 1, Column 2 Syntax error: Malformed token'. From what I can tell the JSON is correctly formatted with all brackets balanced.
Code is running on 64bit Windows 7.
Anyone got an idea why it thinks this (or how I can convert the stringstream_t to a string and see what it actually reads).
change the line
v.parse(s);
to
v = json::value::parse(s)
Could it be that the file is of utf16 encoding?
Or check if your json file has BOM (Byte Oder Mark) at the head by opening it with a hex editor.
Multiple things could go wrong here
Check if the ifstream is able to open the file correctly using the following
if(!f)
cerr << "can't open file";
If this is the case, check if name of the file and location is correct or not
Also replace
v.parse(s);
with
v = json::value::parse(s.str()) /* As parse would take string as input */