Response JSON object or JSON.stringify? - json

Suppose I want to return JSON content
var content = {
a: 'foo',
b: 'bar'
};
What is the best practice to return my JSON data?
A) Return object as is; i.e res.end(content)?
B) JSON.stringify(content) and then call JSON.parse(content) on the client?

The client must always send a string. That's what the protocol says. After all, HTTP is a wide-ranging protocol, and not all languages support JSON objects, let alone JavaScript data.
If you don't convert it to a JSON string, chances are that pure Node will just send it as [object Object], and i'm sure that's not your intention.
As mentioned previously, Express lets you send an actual JS object, and does the JSON string converting for you. Alternately, you can manually convert it.

If you send the response with express's res.json you can send the Object directly as application/json encoded response.
app.get('/route/to/ressource', function(req, res){
var oMyOBject = {any:'data'};
res.json(oMyOBject);
});

Related

selecting a key-value from API response

I have this response from an API:
payment_object = {'acquirer_response': '{"object":"transaction", "pix_expiration_date":"2022-04-28T13:46:01.000Z"}'}
how can i select the pix_expiration_date key??? I have tried:
payment_object['acquirer_response']['pix_expiration_date']
it doesnt work and it returns to me:
TypeError: string indices must be integers
Since you’re looking for json
Here’s a code you can start with, keep the good work :)
import json
#importing json
payment_object = {'acquirer_response': '{"object":"transaction", "pix_expiration_date":"2022-04-28T13:46:01.000Z"}'}
###
dic=json.loads(payment_object["acquirer_response"])
#loading the object
dic['pix_expiration_date']
#it will return 2022-04-28T13:46:01.000Z
Are you the owner of the api? If yes:
Edit the response, because it’s sending an string not an object/dictionary
If No:
Convert the string to an dictionary, like if you using python try json library
Your json is not valid. I don't know what language are you using, this code works for javascript, you can easily translate it to another language
var payment_object = {'acquirer_response': '{"object":"transaction", "pix_expiration_date":"2022-04-28T13:46:01.000Z"}'};
var s=JSON.stringify(payment_object).replaceAll("\\","").replaceAll("\"{","{").replaceAll("}\"","}");
var paymentObject=JSON.parse(s);
console.log(paymentObject['acquirer_response']['pix_expiration_date']); // 2022-04-28T13:46:01.000Z

How to post values from RestAssured to JSon and get a value from it?

{"service_request": {"service_type":"Registration","partner":"1010101","validity":1,"validity_unit":"Year","quantity":1,"center":"1020301","template":"2020301"}}
I have JSON values as above obtained from Request Payload, when I post data from the web page. I want to post this data from RESTAssured in java and want to get the returned value? How can I do that?
I would recommend to check https://github.com/jayway/rest-assured/wiki/Usage#specifying-request-data
I imagine you are trying to do a POST using Rest-Assured.For that simplest and easy way is.. Save your payload as String. If you have payload as JSONObject, use toJSONString() to convert it to String
String payload = "yourpayload";
String responseBody = given().contentType(ContentType.JSON).body(payload).
when().post(url).then().assertThat().statusCode(200).and()
extract().response().asString();
Above code, post your payload to given Url, verify response code and convert response body to a String. You can do assertion without converting to String as well like
given().contentType(ContentType.JSON).body(payload).
when().post(url).then().assertThat().statusCode(200).
and().assertThat().body("service_request.partner", equalTo("1010101"));

How can i make a new single json object by extracting particular fields from realtime json data using node.js

I have the following code which publishes the json data in the specified url using mqtt.The initial data is retrieved from http.
var request = require('request');
var JSONStream = require('JSONStream');
var es = require('event-stream');
var mqtt = require('mqtt');
request({url: 'http://isaacs.couchone.com/registry/_all_docs'})
.pipe(JSONStream.parse('rows.*'))
.pipe(es.mapSync(function (data) {
console.info(data);
var client = mqtt.createClient(1883, 'localhost');
client.publish('NewTopic', JSON.stringify(data));
client.end();
return data;
}))
The following is the subscriber code which subscribes the data that is published (in the above code) through mqtt
var mqtt = require('mqtt');
var client = mqtt.createClient();
client.subscribe('NewTopic');
client.on('message', function(topic, message) {
console.info(message);
});
In the above code, I get all json data in the specified url in 'message'.I need to extract 'id' and 'value' from the received data and make it as a single JSON object and need to publish it to mqtt,so that another client can subscribe only the 'id' and 'value' as json data.
To convert a JSON text into an object, you can use the eval() function. eval() invokes the JavaScript compiler. Since JSON is a proper subset of JavaScript, the compiler will correctly parse the text and produce an object structure. The text must be wrapped in parens to avoid tripping on an ambiguity in JavaScript's syntax.
var myObject = eval(message);
The eval function is very fast. However, it can compile and execute any JavaScript program, so there can be security issues. The use of eval is indicated when the source is trusted and competent. It is much safer to use a JSON parser. In web applications over XMLHttpRequest, communication is permitted only to the same origin that provide that page, so it is trusted. But it might not be competent. If the server is not rigorous in its JSON encoding, or if it does not scrupulously validate all of its inputs, then it could deliver invalid JSON text that could be carrying dangerous script. The eval function would execute the script, unleashing its malice.
To defend against this, a JSON parser should be used. A JSON parser will recognize only JSON text, rejecting all scripts. In browsers that provide native JSON support, JSON parsers are also much faster than eval.
var myObject = JSON.parse(message);
And use it as a Object:
myObject.id;
myObject.value;
Create a object with just id and value :
var idAndValueObj = {};
idAndValueObj.id = myObject.id;
idAndValueObj.value = myObject.value;
Convert to JSON string:
var jsonStr = JSON.stringify(idAndValueObj);

Grails "params" doesn't contain json payload for REST controllers

I'm writing REST API for my app.
Using JSON payload in the POST request:
{
availableAfter: "2014-03-16"
canRead: true
rightName: "dsa"
}
The problem is that, in the controller's params there are no values from payload.
But, despite that, I can read them using properties[*] syntax, like this:
right.properties['rightName', 'canRead'] = params;
right.availableAfter = params.date('availableAfter', 'yyyy-MM-dd');
Properties 'rightName' and 'canRead' are set OK. 'availableAfter' is not(null even if taken with params.availableAfter).
Why is it differs?
UPDATE: Grails v 2.3.6
You have to use request.JSON to get a hold of your JSON-body.
The params object doesn't contain it, unless you serialize your JSON object in the client and pass it as a parameter.

Backbone.js .save() JSON response attribute issue

So my issue is this.
Using backbone to save something in a MYSQL Database.
When I call this.model.save() I am getting a very weird issue.
The model will save the JSON response as an object and will not update the new values instead.
So my attributes in development tools will look something like this.
attributes: Object
0: Object
ID: "4"
Name: "TEST"
Title: "MEOW"
Stuff: "1"
When: "2013-02-14 22:17:14"
The 0 should not be there. I did confirm that the json object is valid so I know that is not the issue here.
It looks like your JSON response is actually an array with a single element, not an object.
The property 0 is created when Backbone calls model.set(response), which in turn copies all keys of the response object to the attributes hash. If an array is passed to set, this is what happens.
You should fix your server to respond with a raw object ({...}) instead of an array ([{...}]). If you're not able to change the server behaviour, you can override Model.parse to unwrap the response on the client:
var Model = Backbone.Model.extend({
parse: function(response) {
return _.isArray(response) ? response[0] : response;
}
});