How to convert JSON format to a string in C++ - c++

Convert JSON format to a string in C++
Have been searching for a solution to convert JSON to a plain string,
but can't find anything remotely suitable.
For example, I have the following data:
{"key1": "value1", "key2": "value2"}
but need it in the following format:
key1: "value1"
key2: "value2"
Would somebody perhaps know of a solution that can achieve this?
Any suggestion would be much appreciated.

[SOLVED]
It seems that I am the only person in the world who gets JSON formatted data from a "REST API" and wants to store it in a variable for further processing in C++.
There seems to be NO solution that converts JSON
{
"variable1": "data1"
}
into this:
variable1 = "data1";
Even though it is unbelievable, but I guess I have to reinvent the wheel after all and code this myself.

Related

Standard way to access a JSON tiddler from javascript

In a Tiddlywiki macro, what is the standard way to load JSON data from a JSON tiddler?
Currently, I've done this:
var my_dict = JSON.parse(this.wiki.getTiddlerText("my_json"))
Loving Tiddlywiki. Thank you!
Unless a better answer comes along:
Yes, this is the way.
But note that in some cases you'll have to use the $tw object (instead of 'this'), for example in a custom parser (such as tiddler of type 'application/javascript' and module-type: 'wikirule'):
var my_dict = JSON.parse($tw.wiki.getTiddlerText("my_json_tiddler"))

How to insert data with SQlAlchemy declarative way

I can add data to my db this way:
a = Model_tbl_name("3", "da", "3", "eheeee", "", "", "", "", "", "", "", "", func.now(), func.now())
db_session.add(a)
db_session.commit()
But i can't do it this way:
data = Model_tbl_name.insert().values({"title_hr":request.form['title_hr'],"text_hr":request.form['text_hr']})
I tried similar, but no help:
data = db_session.Model_tbl_name.insert().execute({"title_hr":request.form['title_hr'],"text_hr":request.form['text_hr']})
My initial motivation is to pass all form data like JSON, i would like to have it like this to work:
data = db_session.Model_tbl_name.insert().execute(json.loads(new_request_form))
In documentation, it is stated it can be done:
http://docs.sqlalchemy.org/en/rel_0_9/core/dml.html?highlight=insert%20values#sqlalchemy.sql.expression.Insert.values
like this:
users.insert().values({"name": "some name"})
But no help, I just can't get it. How can i make it to work, must i provide all JSON data in values() method? How should I write that command to make it work?
Second, how can I grab that error, because, I get no error in Flask, only stops working. I can figure out how to display errors when working with SQLAlchemy declarative way.
P.S. I am using Flask framework, SQLAlchemy, and Python version is 3.4
Well, I don't think you can do db_session.Class_name.
This is what you can do with it: http://docs.sqlalchemy.org/en/rel_1_0/orm/session_basics.html
If your problem is the default values, you can define relevant default values in the Model, and then you can construct an object with less fields.
a = Model_tbl_name(title_hr=request.form['title_hr'],
text_hr=request.form['text_hr'])
If you still want to pass the dictionary, you can do the following:
dataDict = json.loads(new_request_form)
a = Model_tbl_name(**dataDict)
db_session.add(a)
db_session.commit()
IMHO - the first method is more readable and reliable (you can check for validity of the params - that they match the object) -> at the end of the day, more secure...
if you need the insert way (let's say because you want to pass .prefix_with('IGNORE'))
you can do it like this
session.execute(Model_tbl_name.__table__.insert().values(
col1=val1, col2=val2).prefix_with('IGNORE'))
it works good with Connection class:
import sqlalchemy as sa
conn.execute(
sa.insert(Model_tbl_name).values(
{
Model_tbl_name.field1: 'value1',
Model_tbl_name.field2: 'value2',
Model_tbl_name.field3: 'value3',
}
)
)

Convert ObjectId of mongodb object to string

How to convert ObjectId of mongodb object in string format.
ObjectId('5323d54c41cf6e0ffab13384')
I have above ObjectId and i want to convert this ObjectId back to string name from which its generated. Is there any way that i can directly display name from above ObjectId in django template. Please suggest.
Just get the string representation:
ObjectId('5323cc2770fde63cf1146ba3')
>>> str(o)
'5323cc2770fde63cf1146ba3'
Also see the documentation
From your comments though you do not seem to have a full understanding of what an ObjectId is and I would suggest you do some reading on that. Also read up on documents in general.
What you seem to be asking, which is not how your question reads is how do I get the "properties" from an ObjectId you received after you saved a "document" or, otherwise in some form or another. You get the "document" by querying the database:
var doc = db.collection.findOne({ _id: ObjectId('5323cc2770fde63cf1146ba3') })
And then you can access the "properties" of the document you received. So the resulting "document" you fetch might look like this:
{
"_id": ObjectId('5323cc2770fde63cf1146ba3').
"name": "Neil",
"favouriteColour": "Blue",
"age": "Don't Ask"
}
An ObjectId by itself contains no magic information. It is a primary key, to a document that exists in the collection.

Is there something like Regular Expressions, but for matching JSON instead of strings?

Regular expressions allow us to specify some format a string should match, and then test to see if a string matches, find out where it matches, and capture backreferences.
I'd like to have something like this for JSON. Consider:
{ "title": "My blog entry",
"author": { "name": "Joe", "id": 4324132 },
"comments: [
"first!!!",
"Very insightful!",
"A++ would read again"
]
}
You could match this with something like:
{ "title": (title),
"author": *,
"comments": [
"first!!!",
...
]
}
(Which would return successful, and bind the capture title to the value "My blog entry")
That's just an example. Would be useful for everything from validating API responses to extracting information from JSON to even (a la RE substitution) transforming JSON.
Anyone seen anything like this? Surprisingly, searching for regexes and JSON in the same context only leads to people trying to parse JSON with regexes. Ew.
There are a few tools that could help you do this, although not exactly with regex's.
First it seems that what you need is validating your data, for that you can use JSON Schema.
Second, to extract the title, assuming you don't want to decode the json string, you can either use JSONPath if you are in JS or PHP, or you could try JsonGrep for CLI or Python. There is also jshon for CLI parsing.
You should check out json:select - it's like CSS-selectors for JSON ... which is as close to a "regex" as you get for dealing with structured data.
If you want to play with it from the command-line, check out underscore-cli, which exposes "select" as one of its commands.
jsonmatch is a library that does the validation part of what you're looking for. It's a bit simpler/lighter-weight than the JSON Schema library referenced in the accepted answer above. If you'd like to extend it to do capturing, pull requests are warmly welcomed ;).

Django JSONField encoding floating point values as strings?

I'm saving the following simple, valid JSON object to a model in my Django app:
{
"start_date": 1311471044.24338
"post_count": 25
}
The model looks like this:
from django.db import models
from django_extensions.db.fields import json as json
class UserProfile(models.Model):
data = json.JSONField()
To read the posted data, I basically do
posted_data = request.FILES.get('posted_data').read()
json_data = simplejson.loads(posted_data)
The data then contains the expect type (float)
logging.debug( "start_date type: " + str(type(json_data.get('start_date'))))
logging.debug( "post_count type: " + str(type(json_data.get('post_count'))))
>> 2011-07-24 10:03:01,636 DEBUG start_date type: <type 'float'>
>> 2011-07-24 10:03:01,636 DEBUG post_count type: <type 'int'>
I then save the data like this:
user_profile.data = json_data
user_profile.save()
and then I read the data back, integers are fine, but floating point numbers are quoted, for example:
print user_profile.data
{
"post_count : 25
"start_date": "1311471044.24338"
}
How can I prevent floating point numbers from being turned to strings unnecessarily?
Edit:
May have found an explanation here: Rails JSON Serialization of Decimal adds Quotes
I still would be interested in other explanations though.
This answer seems to be the best explanation:
The only "safe" way to hand decimals from language A to language B is to use a String. If your json contains "rating": 98.79999999999999 it will probably be converted to 98.79999999999998 by your JavaScript runtime.