convert mongodb object to javascript object - javascript

I pass a config file to another node.js module when starting it. The config file contain the following json:
"resolution": {
"activated": true,
"types": [
{"of": 23}
]
}
When I print the received types array in the called node.js module, it looks like
console.log('types array: '+ this.config.resolution.types)
//output
types array: [object Object]
if I tried to print the text by using JSON.stringify(), I get the following result
[{"of":23}]
My problem start when I try to replace the types array with a list retried from a mongodb database. my code looks like:
"resolution": {
"activated": true,
"types": [
savedTypes
]
}
Now when I print the received types config, it looks like this:
types array: { _id: 5ab9fe8fd1f64303cd98f122, of: 23, __v: 0 }
and the called node module is not working properly with this config. How can I cast this to an object? I tried to use
JSON.parse(savedTypes)
and get the error
SyntaxError: Unexpected token _ in JSON at position 2

If you use mongoose, I think that the correct form is using ToJSON() function.
Otherwise, you can use JSON.parse(JSON.stringify(data)); But I think that de first form is better.
=)

Alternatively you could use .toObject() method from javascript to convert mongoose object into javascript object.
Here is a reference link to dig out more
https://alexanderzeitler.com/articles/mongoose-tojson-toobject-transform-with-subdocuments/

Related

Access value from a string object - Javascript

Not sure why I am not able to access the keys from a string object
data looks like this
I am getting this data from a python variable
const data = '{regression: {success: 7310, total: 14154, failed: 4665, unstable: 2104, aborted: 75}, stable: {success: 2699, total: 4252, failed: 462, unstable: 15, aborted: 1076}, patch: {success: 2824, total: 5494, failed: 2518, unstable: 39, aborted: 113}}'
I need to extract the keys regression, stable, patch and eventually the details of how many test cases were in success, total, failed etc.
Tried to change the string to object using JSON.parse(data) but it gives error as its not an object.
How can I extract the keys and value in this case
There is an easy approach to make this work.
In your Python code, use the json.dumps() method to convert a Python dictionary into valid JSON, like below.
import json
dictonary = {
"name": "Name",
"age": 0
};
print(json.dumps(dictionary)) # Returns JSON
Then, in your JavaScript, add the following code.
const data = "{\"name\": \"Name\", \"age\": 0}";
console.log(JSON.parse(data)); // Returns a JavaScript object
The JavaScript code should now return a JavaScript object without any errors.

Calling strange field of JSON in NodeJS

im working with NodeJS and services SOAP in XML.
To call the soap I use strong-soap and to transform XML in JSON use xml2js.
All ready works good, the response shows like:
{ 'SOAP-ENV:Envelope': { '$':
{ 'xmlns:SOAP-ENV': 'http://schemas.xmlsoap.org/soap/envelope/',
'xmlns:ns1': 'http://sandbox.coordinadora.com/agw/ws/guias/1.5/server.php',
'xmlns:xsd': 'http://www.w3.org/2001/XMLSchema',
'xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance',
'xmlns:SOAP-ENC': 'http://schemas.xmlsoap.org/soap/encoding/',
'SOAP-ENV:encodingStyle': 'http://schemas.xmlsoap.org/soap/encoding/' },
'SOAP-ENV:Body': [ [Object] ] } }
But in javascript I can call response.SOAP-ENV:Body because show me error.
What I can do to handle this data?
- and : aren't valid characters in javascript variables, so you'll have to use bracket notation like this:
let body = response['SOAP-ENV:Body']

JSON parsing and stringify

I am currently working on a Javascript project where I have to parse tons of data. The project requires that I parse some JSON data and bring specific data into another array. Right now, I am using the JSON.stringify method and I can console.log all of the data that I need. The data looks something like this:
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Polygon",
"coordinates": [
[
[
-85.3865810000125,
33.90171899971196
],
[
-85.38659500025622,
33.9017919996593
],
yes, this is not all that data-it is about 1200 pages long! I only pasted in the top segment of it. All I really need is how to get to the coordinates aspect of it and into an array. So what I am currently doing is this:
var work = JSON.stringify(response, null, 4)
console.log(work);
Which gives me the above response. However, I am not that familiar with JSON.stringify so if I do:
console.log(work.type);
Attempting to see what the value is for type, I get a response of undefined. Now if I try doing this:
var work = JSON.parse(response)
console.log(work);
I get a response of: VM296:1 Uncaught SyntaxError: Unexpected token o in JSON at position 1
Thus, I cannot get the data parsed which I want to get to which will be the coordinates data. Any help with using stringify would great help me. I have read a lot about how it turns the data into a string but have not really seen a lot about how to parse it. Do I have to use parse? Thank you for your help!
You dont' have to use stringify or parse for this. The response object you are receiving is already a javascript object so you can reference its properties normally
response.type; // => "FeatureCollection"
If you try and stringify the response it will lose its type property, for instance:
typeof "some string".someProperty; // => undefined

Issue with JSON.parse , don't know why is not parsing everything

I'm developing a web app with Node.js using Sails framework(based on Express) and i'm using a third party image solution called Transloadit (no need to know Transloadit).
Anyway, that's not the problem, i'm been able to implement the Transloadit form and receive the information from their API.
My problem is that, Transloadit gives me the response as a String, and I need to access the response objects, so i'm using var objRes = JSON.parse(req.body.transloadit); to parse it to an JSON object, and when I console.log(objRes); the object is not correctly parsed, i get this: (see all JSON here https://gist.github.com/kevinblanco/9631085 )
{
a bunch of fields here .....
last_seq: 2,
results: {
thumb: [
[
Object
]
]
}
}
And I need the data from the thumb array, my question is, Why is doing that when parsing ?
Here's the entire request req.body object: https://gist.github.com/kevinblanco/9628156 as you can see the transloadit field is a string, and I need the data from some of their fields.
Thanks in advance.
There is nothing wrong with the parsing of the JSON -- in fact there is no problem at all.
consol.log limits the depth of what it is printing which is why you are seeing [object] in the output.
If you want to see the full output in node.js then just use the inspect utility like this;
console.log(util.inspect( yourobject, {depth:null} ));
and that will print the entire content.
Note that this is just an artifact of console.log printing it.

Result of BsonDocument.ToJson fails when used in JSON.parse

I'm retrieving data from MongoDB and then sending it to client:
var bsonDocument = ... retrieve from database ...
var dto = new Dto { MyBson = bsonDocument.ToJson() };
On the client I'm trying to parse MyBson property using JSON.parse.
I'm getting the following error: SyntaxError: Unexpected token N. I guess this is because one of the properties looks like this:
{ ..., "SomeIntProp" : NumberLong(70) }
JavaScript parser simply doesn't understand Bson data type: NumberLong.
How should I convert BsonDocument to JSON so that the output would omit NumberLong?
There is no easy way to solve this, I worked out a solution by writing my own parsing function which understands the MongoDB BSON types and does the conversion. The native JSON.parse only understands the types used by the JavaScript. Here is my version:
https://gist.github.com/Hrish2006/8270187
You probably will not need the html snippets in the code.

Categories