JSON parsing with JsonResult and JavaScript - javascript

Environment: ASP.net MVC:
Given anonymous structure as such:
var test = new {
name = "me",
age = "100"
};
that then gets parsed as
result = Json(test)
data = result.Data // Comes back with { name = "me", age = "100" }
Which then gets successfully passed into a JS function, how do I go about using that as a JSON object, so that I can do something like
function(data) // Where data = { name = "me", age = "100" } or similar
{
var name = data.name // "me"
}

Try
var object = eval('(' + data + ')');
then you should be able to do object.name.

The JSON is invalid, it should be
{
"name" : "me",
"age" : "100"
}
And new {..} doesn't do anything meaningful -- the object literal is alone sufficient.

Related

POSTMAN - How to set environment value for nested object in single request?

Im trying to sign few fields and send the signed field as another field in an request.that is inside of an nested object..Im trying to setEnvironmentvariable but it is setting the same value again..
{
"id" : "1234",
"ref" : "REF05",
"details": [
{
"traceNumber": "201902120005",
"amount": "100",
"customerNumber": "0924",
"signature": "{{signature}}"
},
{
"traceNumber": "201902120007",
"amount": "120",
"customerNumber": "0739",
"signature": "{{signature}}"
}
],
"date": "20210619"
}
Im signing traceNumber+amount+customerNumber fields by private key and passing the value to signature fields which works fine with single object. if i try with multiple objects it just set the last calculated signature.
if (globals['jsrsasign-js'] === undefined) {
console.log("jsrasign library not already downloaded. Downloading now. ")
pm.sendRequest({
url: "http://kjur.github.io/jsrsasign/jsrsasign-latest-all-min.js",
method: "GET",
body: {}
}, function(err, res) {
postman.setGlobalVariable("jsrsasign-js", res.text());
doHttpSig();
});
} else {
doHttpSig();
}
function doHttpSig() {
var navigator = {}; //fake a navigator object for the lib
var window = {}; //fake a window object for the lib
eval(postman.getGlobalVariable("jsrsasign-js"));
let pk = postman.getGlobalVariable("PRIVATEKEY")
let pks = pk.split(/\\n/)
//console.log("pkss Key", pks);
privateKey = ""
for (let i = 0; i < pks.length; i++) {
privateKey += pks[i] + "\n"
}
var reqBody = JSON.parse(request.data);
for (let i = 0; i<reqBody.details.length; i++) {
var fields = reqBody.ref+reqBody.details[i].traceNumber+reqBody.details[i].amount+reqBody.details[i].customerNumber;
var signature_algo = "SHA1withDSA";
var payload = fields;
var sig = new KJUR.crypto.Signature({
"alg": signature_algo
});
sig.init(privateKey);
sig.updateString(payload);
var sigValueHex = sig.sign();
var sigBase64 = hextob64(sigValueHex);
postman.setEnvironmentVariable("signature", sigBase64);
}
}
This is my postman prescript. some one pls let know hoe to acheive this.
I want to add SettlementValues object in the Environment variable and when I add, I see the value as [object,Objet] instead of complex object.
var settlementValues = new Object();
var requestData = pm.request.body.raw;
var requestjson=JSON.parse(requestData);
settlementValues.TransactionCode=requestjson.ProcessingCode.TransactionCode;
settlementValues.TransactionAmount= requestjson.TransactionAmount.Amount;
settlementValues.ReferenceNumber=requestjson.RetrievalReferenceNumber;
settlementValues.BanknetReferenceNumber=requestjson.NormalizedData.MastercardData.BanknetReferenceNumber;
console.log(settlementValues);
pm.environment.set("SETTLEMENTOBJECT",settlementValues);

How to define an object variable like this in JQuery?

I would like to create a variable and populate data and make the output of the variable like the following pseudo code:
myObj = {
"Title":"Test",
"Paragraphs":
[
{
"Order":"1",
"Id": "2"
},
{
"Order":"2",
"Id": "1"
},
{
"Order":"3",
"Id": "2"
}
]
}
And use JQuery to POST to MVC controller action at the back end using a defined data model:
public class TemplateBuilderViewModel
{
public string Title { get; set; }
// Not sure if I should use Dictionary or something else
public Dictionary<int, int> Paragraphs { get; set; }
}
I am not sure how to declare the variable and populate data into the variable with the data structure I want in the output.
Any suggestions? Thank you.
This is what I get working in the end in JQuery.
Declare an array type, use push to insert values and assgin the arrary variable into the object type variable.
var dict = [];
for (i = 1; i < counter; i++) {
var paragraphId = Id;
var order = order;
dict.push({
"ParagraphId": paragraphId,
"ParagraphOrder": order
});
}
var templateBuilder = {
TemplateTitle: title,
ParagraphTitle: "",
ParagraphTitleList: undefined,
ParagraphText: "",
ParagraphOrder: dict
};

pass json values across pages

I have defined a json object as
function getPost()
{
var fname = document.getElementById("fname").value;
var lname = document.getElementById("lname").value;
var v = {
"name": {
"firstname": fname,
"lastname": lname
}
};
}
How can I make this JSON variable v accessible to other pages. I want to pass the JSON data across pages.
You can store data locally within the user's browser using localStorage or SessionStorage(more information) to access your data in all pages.
Take a look at this example:
localStorage.setItem('a', '{ "name" : "test"}');
eval("var myObj = " + localStorage.getItem('a'));
myObj.name; // test

Getting property key from json object

Preamble: I'm Italian, sorry for my bad English.
I need to retrieve the name of the property from a json object using javascript/jquery.
for example, starting from this object:
{
"Table": {
"Name": "Chris",
"Surname": "McDonald"
}
}
is there a way to get the strings "Name" and "Surname"?
something like:
//not working code, just for example
var jsonobj = eval('(' + previouscode + ')');
var prop = jsonobj.Table[0].getPropertyName();
var prop2 = jsonobj.Table[1].getPropertyName();
return prop + '-' + prop2; // this will return 'Name-Surname'
var names = [];
for ( var o in jsonobj.Table ) {
names.push( o ); // the property name
}
In modern browsers:
var names = Object.keys( jsonobj.Table );
You can browse the properties of the object:
var table = jsonobj.Table;
for (var prop in table) {
if (table.hasOwnProperty(prop)) {
alert(prop);
}
}
The hasOwnProperty test is necessary to avoid including properties inherited from the prototype chain.
In jquery you can fetch it like this:
$.ajax({
url:'path to your json',
type:'post',
dataType:'json',
success:function(data){
$.each(data.Table, function(i, data){
console.log(data.name);
});
}
});

How to use a variable as a json atribute?

Hello im working in a generic function that sends an ajax request according with the selection made:
$('#selectAcao, #selectAno').change(function(){
var sthis = $(this);
var sthisTipo = sthis.attr('rel');
var sthisName = sthis.attr('name');
var params = {
"tipo": sthisTipo,
sthisName : sthis.children('option:selected').val(),
"atualiza" : true
}
$.atualizaSelect(params);
});
All I want is pass a "sthisName" variable as a property in "param":
var params = {
"tipo": sthisTipo,
sthisName : sthis.children('option:selected').val(),
"atualiza" : true
}
how can i do this?
That isn't JSON. JSON is a data serialisation format. What you have is a JavaScript object literal.
There is no way to define a property name using a variable at creation time for a JavaScript object.
You have to create the object first, and then add the property.
var myObject = {};
myObject[string_containing_property_name] = some_value;

Categories

Resources