Convert ObjectId of mongodb object to string - django

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.

Related

How to convert JSON format to a string in 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.

Can creationTime and other Directory meta-fields be used in a query?

I'm trying to filter the list of users returned from Directory.Users.List, and want to use the creationTime value in the filter. According to this:
Search for users
...you can use Date fields in comparisons, however when I try something like:
creationTime>=2016-06-30 (or the same value quoted)
...I get:
Caused by: com.google.api.client.googleapis.json.GoogleJsonResponseException: 400 Bad Request
{
"code" : 400,
"errors" : [ {
"domain" : "global",
"message" : "Invalid Input: creationTime>=2016-06-30",
"reason" : "invalid"
} ],
"message" : "Invalid Input: creationTime>=2016-06-30"
}
The message isn't particularly helpful - is this a syntax issue with the query, or is it the case that the field isn't available for query (it isn't listed in that article, but it is part of the JSON response)?
The article specifies the format for Date field queries, however this field also includes a time component, so I tried to also replicate the exact format that shows in the JSON, with the same result.
Also, same result in the Try it! section of the Users reference page.
Also also, tried using a numeric value (Date.getTime(), in effect) - same error.
Thanks...
P.S. Interestingly, Google does document how to search on date fields for Chromebooks, and it's entirely different than they imply for users. I still can't use creationTime with this, but it does work for Chromebooks. The other part of this is that it refers to fields that aren't documented, and why I try to use the documented field (e.g. lastSync vs. sync), it fails with the same message. This whole thing seems half-baked.
View Chrome device information
Only the fields listed in the table are searchable via the users.list search.
A workaround (I don't know if this is suitable for you) may be to push the data you want to use in a search into custom user fields. These fields are searchable.

Get value in a post request, Django

am getting the following post data in my django app
POST
Variable Value
csrfmiddlewaretoken u'LHM3nkrrrrrrrrrrrrrrrrrrrrrrrrrdd'
id u'{"docs":[],"dr":1, "id":4, "name":"Group", "proj":"/al/p1/proj/2/", "resource":"/al/p1/dgroup/4/","route":"group", "parent":null'
am trying to get the id value in variable id i.e "id":4 (the value 4). When I do request.POST.get('id')I get the whole json string. u'{"docs":[],"dr":1, "id":4, "name":"Group", "proj":"/al/p1/proj/2/", "resource":"/al/p1/dgroup/4/","route":"group", "parent":null' How can I get the "id" in the string?
The data you are sending is simply a json string.
You have to parse that string before you can access data within it. For this you can use Python's json module (it should be available if you're using Python 2.7).
import json
data = json.loads( request.POST.get('id') )
id = data["id"]
If you somehow don't have the json module, you can get the simplejson module.
For more details, refer this question : best way to deal with JSON in django
That's happening because id is string, not dict as it should be. Please provide your template and view code to find source of problem.

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 - Serializing model with additional data

I am trying to serialize some model data along with some extra information like so:
data = {
'model_data': serializers.serialize('json', SomeModel._default_manager.all(), fields=('name','last_updated')),
'urls': {
'updateURL':'http://www.bbc.co.uk',
},
}
json = simplejson.dumps(data)
It seams my 'model_data' object is being serialized twice as it seems to be returned as a string and not a valid json object:
Object
model_data: "[{"pk": 1, "model": "models.SomeModel", "fields": {"last_updated": null, "name": "Name test"}}]"
urls: Object
What am I doing wrong here?
How about having the value of the model_data field be handled again by another JSON processor? I think it will be the same, since the JSON processor always expects a string that is always in the correct format.