getting valid JSON in Nodejs from Posted data - node.js

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.

Related

nodejs accept data from api problem with json

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.

Replace key-value pair in an object with Google Apps Script

I am making a call to an API for a commercial product using Apps Script. Unfortunately, the resulting object has several key-value pairs that contain the id from a linked table.
I can easily get the standard values and have written code to find the related name value and add it to the object. I would prefer to add the name in the same location as the original id. But, when I add a new key, it is added to the end of the object.
I want the name in the same location as id so when I insert it into a sheet, the columns will still be in order.
This is my object:
var json = {id: 4730183,name: "A A", customer_source_id:123, company: "NE Company"};
This is my desired object after replacing the id with the name:
var json = {id: 4730183,name: "A A", source:"CRM", company: "NE Company"};
Basically, I want to find customer_source_id in the object and replace it with source.
I can't use indexOf and splice because the object is not an array.
What is the best way to do this? Do I have to convert it to an array first and then back again?
A quick answer would be:
var obj = {id: 4730183,name: "A A", customer_source_id:123, company: "NE Company"};
var json = JSON.stringify(obj);
json = json.replace("customer_source_id","source")
The better answer is:
#Waqar Ahmed is correct. JavaScript objects are unordered. In your example "var json" is an object not JSON. You can make it JSON with JSON.stringify(json). But once the JSON is parsed into an object it again becomes unordered. You should not use it to store ordered data.
I am not sure if it is efficient, but you can iterate through the keys and build a new json object like this:
var newjson = {};
for(var key in json){
if(key === 'customer_source_id'){
newjson.source = [NEW VALUE TO DISPLAY];
}else{
newjson[key] = json[key];
}
}
json = newjson;
But, like #Waqar and #Spencer said, the object is not used for ordered data.
You can do his only in java script array. Not in JSON. JSON is meant to be addressed by keys, not by index.Change your json to
var json ={id: 4730183,name: "A A", customer_source_id:null, items : [] company: "ESI"};
Now you can insert items using push method of array.
json.items.push('My Item');

How can I get the original order of files in the request?

I'm using express and multer. In the following the files are in a random order. The order of the files is important to this particular request. How can I obtain the original order from the request? All I need is an array of original names.
/* POST Put user items. */
router.post('/put', upload.array('useritem'), function (req, res, next) {
// req.files is always in a different order.
});
Node doesn't guarantee the index order of arrays. See this question for more info: Nodejs Order of properties guarantee
As pointed out emphatically, my statement above is incorrect. The correct statement would have been that you should not relay on the order of properties in an object if you have used JSON.stringify() to convert the object to JSON and then sent it as the payload of a request.
Although my original statement is apparently incorrect, it is a problem I've run into myself — where array values show up in the wrong order on my server — and I solved it like illustrated below. Amit's suggestion in the comments above could be the source of the problem. Specifically that it's your client side javascript that's not originally entering the files in the order you'd expect.
Whatever the cause, you'll have to do some work on the client side to add an 'artificial' index to each file and then pass them through as an array of objects.
So instead of this:
var files = ['file1.jpg','file2.jpg','file3.jpg'];
You'll need to pass an object to your backend like so:
var files = [
{ index : 0, file : 'file1.jpg' },
{ index : 1, file : 'file2.jpg' },
{ index : 2, file : 'file3.jpg' },
];
And then you'll need to sort the array of objects once it's received by your backend instance, like so:
files.sort(function(a, b) {
return a.index - b.index;
});
And then you can loop through the files array and do what you will:
var justFiles = [];
async.each(files, function(file, iterate){
justFiles.push(file.file);
return iterate();
}, function(result){
console.log(justFiles);
});
And the output would be:
'file1.jpg','file2.jpg','file3.jpg'

From my http GET JSON request to CouchDB I want to get the nested keys and values out and remove total rows and id

My GET JSON brings back from COUChDB
{"total_rows":6,"offset":0,"rows":[
{"id":"51585142d8f2851d34c9b7dc8c003997","key":"itemName","value":{"nestedkey1":"nestedvalue1","nestedkey2":"nestedvalue2","nestedkey3":"nestedvalue2","nestedkey4":"nestedvalue4","nestedkey5"}},
I want to remove {"total_rows":6,"offset":0,"rows":[
{"id":"51585142d8f2851d34c9b7dc8c003997","key":"itemName"
So I am left with the wrapper/parent "value" that has the nested keys and nested values I really want and so it is presented in the following JSON format {"nestedkey1":"nestedvalue1","nestedkey2":"nestedvalue2","nestedkey3":"nestedvalue2","nestedkey4":"nestedvalue4","nestedkey5"}}, as my json
I've tried CouchB mapping/views and jquery client side function/result filtering but I'm new to this and could use some insight into achieving my objective
You should be able to achieve this using jQuery on the client side. You could do this in the success callback of get()
var value = [];
$.get( "url/to/view", function( data ) {
$.each(data.rows, function(index, row){
value.push(row.value);
});
});
That way, you have the rows in data.

Get a single value from document

Is there a possibility in CouchDB to retrieve a single value from a document? For example, I have a document with 10000 keys like this:
{
"_id": "8098091cc795acde43cd45335373cc92",
"_rev": "2-6d2e0ac43618388cc958b91e5015bba5",
"1":"some value",
"2":"another value",
...
"10000":"last value"
}
and I don't want to parse the whole document each time but just want to get a value of key "2". Is this possible?
EDIT:
Of course, before asking this question I looked through the docs and googled around this but haven't found such possibility. But I'm wondering why this is not possible? In my understanding it is not too much difference between view and document since both of them are sets of key-value pairs, but it is possible to get single value from view using ?key=... in the query string and not possible to do the same for document. Why?
You can use a CouchDB show function to process a document on the server and send arbitrary data to the client. Show functions can do simple things like extracting a single value from the document; or they can convert to a completely different content-type such as XML.
For example:
In database db
which has design document _design/example with show function one_field
you want to fetch document with ID doc_id
but only retrieve the field some_field which has a value "I am the some_field value!"
That query would be:
GET /db/_design/example/_show/one_field/doc_id?name=some_field
The show function would look like this:
function(doc, req) {
// _show function to extract one field
var field_name = req.query.name; // Set to e.g. "some_field"
var field_value = doc[field_name];
return { "code": 200 // HTTP status code
, "headers": // Response headers
{ "content-type": "text/plain" }
, body: field_value
};
}
The design document would look like this:
{ "_id": "_design/example"
, "shows":
{ "one_field": ... } // Paste the above function as a string.
}
CouchDB will return
HTTP 200 OK
Content-Type: text/plain
Content-Length: 26
I am the some_field value!
No. CouchDB is a document oriented DB, so it doesn't support more granular access to the data beyond the overall document itself.
It gives you fine grained indexing, but not actual access.

Resources