nodejs accept data from api problem with json - node.js

I am trying to get some JSON data from the API provided by the vendor, but i am getting error i try google it, in many comments people say to use JSON.Stringify but in my case JSON.Stringify didnt help me it returns an empty array like {}
repose from the api are as follow
[{ SYMBOL: 'FOREX',
CODE: 'REG',
LST: '219.50',
LTP: '12:52:35'}]
but my desire response is
[{ "SYMBOL" : "FOREX",
"CODE": "REG",
"LTP": '219.50',
"LST": '12:52:35'}]

If the JSON result provided by the vendor's API is indeed this :
[{ SYMBOL: 'FOREX',
CODE: 'REG',
LST: '219.50',
LTP: '12:52:35'}]
I have to inform you that this is invalid JSON. In JSON, the properties should be strings between double-quotes, otherwise it cannot be parsed.
Your desired response is the correct form. There is likely an error in the way the vendor is forming the output.
tl;dr : Your vendor's API is giving you a JavaScript Object, not JSON.

Your response is on text, To convert text to JSON string,
let text = `[{ SYMBOL: 'FOREX',
CODE: 'REG',
LST: '219.50',
LTP: '12:52:35'}]`
let jsonStr = JSON.stringify(eval("(" + text + ")")); // Convert Object String to JSON
console.log(jsonStr);
Note : Make sure that your vendor is trusted source, Because eval opens up your code for injection attacks, If your are worry about this, Please contact your vendor to provide JSON response.
Reference : Convert object string to JSON

Ok so what i did is use STRINGFY as a middleware and that solve my problem thanks for your help guys really appreciatable.

Related

How to Json convert normal string using nodejs

I have the below result, I want its show normal words like description: hello test, address:London in nodejs
delta result {"description":"HELLO Description Edit","address":{"street_address":"Business Edit","city":"Bradford EDIT"}}
I want like description: hello test, address:London
var pusthistory = new JobHistory({ changetype: 'Updated', details: JSON.stringify(delta) });
If your question is to convert a JSON to a normal string,
use
JSON.stringify() method to do that
Or if you want to parse JSON string to JSON,
You can parse it using JSON.parse()

How to edit a .js file with nodes

I'm trying to figure out if it's possible to simply open up a JSON data script with nodejs and edit it... as javascript ...
// my json data
{
people : [{
name : 'Joe',
hobby : 'hunting',
job : 'accountant'
},{
name : 'William',
hobby : 'chess',
job : 'manager'
}]
}
i just want to do something like e.g.
people[0].name = 'Joseph'
so i'm trying
fs.open('/path/to/file', 'r+', function(err, fd){
// not really sure what to do from here...
})
there are plenty of answers about how to read/write text files... i just thought there might be an easier way for the case of a file in JSON
Whoops this is a repeat question - please see an earlier response here
How to update a value in a json file and save it through node.js
Parse the JSON using JSON.parse(), modify the parsed object, turn it back into a new string using JSON.stringify(), then save the string to the file.

getting valid JSON in Nodejs from Posted data

am getting json data as a response in the following format
{ '{"select":"samplec","value":"nation"}': '' }
How can i get a valid json data like
'{"select":"samplec", "value": "nation"}'
That is sort of an odd response to be getting, but in any case for this particular example you would do something like:
// Get the keys of your weird response object
var keys = Object.keys(response);
// The first key is a JSON string, so parse that
var obj = JSON.parse(keys[0]);
If the response had more than one key, you could loop through them all and create an array of objects. I would look into why the response was formatted the way it is, though, and see if you can't get the JSON strings delivered in some other way.

Programming with node.js and mongoose. Error id want to pass the value to update registration

I'm learning to use with mongoose and node.js when editing to generate a content that gives me the error: 500 TypeError: Can not read property 'ObjectID' of undefined. Check whether the parameter that I send comes empty and is not.
Remove the option and gives me that error when saving the data did not find the method I use to save some registry update.
If I can help as I have code in https://github.com/boneyking/PruebaNode.git
First of all, please provide code or at least a link to the code. A link to your github repo is not cool !!!
Now back to the question... Add an id to your model and get it like other types:
var SUPER = mongoose.model('Producto',{
nombre: String,
descripcion: String,
precio: Number,
id: mongoose.Schema.Types.ObjectId
});
SUPER.editar = function(newData, callback){
SUPER.findOne({id: newData.id}, function(e,o){
o.nombre = newData.nombre;
o.descripcion = newData.descripcion;
o.precio = newData.precio;
SUPER.save(o);
callback(o);
});
}

How to preserve types in query strings

Im trying to put together an API that would consume json data, and I'm having problems preserving variable types.
caveat: I'm using Node.js
Given the data:
{
id: "string",
data: [
{input: [0,1,0], output: [1,1]},
{input: [1,0,0], output: [1,0]}
]
}
When i make a jquery ajax post request with that data it is transfered as:
data[0][input][] 0
data[0][input][] 1
data[0][input][] 0
data[0][output][] 1
data[0][output][] 1
data[1][input][] 1
data[1][input][] 0
data[1][input][] 0
data[1][output][] 1
data[1][output][] 0
id string
or: id=string&data%5B0%5D%5Binput%5D%5B%5D=0&data%5B0%5D%5Binput%5D%5B%5D=1&data%5B0%5D%5Binput%5D%5B%5D=0&data%5B0%5D%5Boutput%5D%5B%5D=1&data%5B0%5D%5Boutput%5D%5B%5D=1&data%5B1%5D%5Binput%5D%5B%5D=1&data%5B1%5D%5Binput%5D%5B%5D=0&data%5B1%5D%5Binput%5D%5B%5D=0&data%5B1%5D%5Boutput%5D%5B%5D=1&data%5B1%5D%5Boutput%5D%5B%5D=0
What I need to be able to do is decode the data on the server side but all the values of my arrays in data are being transformed to strings.
Is there a technique for preserving the type of a value ie: "string" or "int" etc?
I'm currently using the qs module on npm to parse my POST request body.
JQuery serializes any object passed in the data option of an AJAX request into application/x-www-form-urlencoded format (just like a query string). What you want is to JSON.stringify() your object and pass the resulting string as data, along with setting the Content-Type as the previous answer mentions.
Remember that the dataType option specifies how jQuery should deal with the response to the request, not how to encode the body of the request (I've gotten burned by this one).
Since it is a JSON server, set Content-Type: application/json in the POST request, so you'll be parsing an object rather than a string. The object will retain data types. Use req.is('application/json') on the server to ensure that the request is of type 'application/json'.
Here is a working solution, hope it helps.
$.ajax({
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json',
url: 'http://localhost:3000/endpoint',
success: function(data) {
//TODO: do something with data
}
});

Resources