I want to create a dynamic json string.
Json looks like:
{
"getHostedPaymentPageRequest": {
"merchantAuthentication": {
"name": "x345dsfg",
"transactionKey": "456tyYYUU7876"
},
"transactionRequest": {
"transactionType": "authCaptureTransaction",
"amount": "20.00",
"profile": {
"customerProfileId": "123456789"
}
}
}
}
The values in json like name, transactionKey, transactionType, amount, customerProfileId will vary for different users.
I am following this method to create json:
var getHostedPaymentPageRequest = new Object();
var merchantAuthentication = {};
merchantAuthentication.name = "x345dsfg";
merchantAuthentication.transactionKey = "456tyYYUU7876";
var transactionRequest = {};
transactionRequest.transactionType = "";
transactionRequest.amount = "20.00";
var profile = {};
profile.customerProfileId = "123456789";
transactionRequest.profile = profile;
getHostedPaymentPageRequest.merchantAuthentication = merchantAuthentication;
getHostedPaymentPageRequest.transactionRequest = transactionRequest;
getHostedPaymentPageRequest = JSON.stringify(getHostedPaymentPageRequest);
But its not giving back the right values.
How do I make a valid json in the desired format?
The provided code (if we add a console.log on getHostedPaymentPageRequest) displays the following result (which is how it should behave):
{
"merchantAuthentication": {
"name": "x345dsfg",
"transactionKey": "456tyYYUU7876"
},
"transactionRequest": {
"transactionType": "",
"amount": "20.00",
"profile": {
"customerProfileId": "123456789"
}
}
}
The only meaningful difference that I see between this and the expected result is that in your expected result the JSON starts with
{
"getHostedPaymentPageRequest": {
...
}
}
For that you have to wrap your getHostedPaymentPageRequest object in another object. So instead of doing this:
getHostedPaymentPageRequest = JSON.stringify(getHostedPaymentPageRequest);
add braces like this:
getHostedPaymentPageRequest = JSON.stringify({ getHostedPaymentPageRequest });
You can use this as a reference..
I've split the object based on what it's doing and I've obtained two separate objects: merchantAuthentication and transactionRequest. For each object I created a separate function who return an individual object, because in the future you might want to add more fields therefore it will be easier to you to know were to place them :)
function createMerchantAuthObject() {
let merchantAuth = {};
merchantAuth.name = "x345dsfg";
merchantAuth.transactionKey = "456tyYYUU7876"
return merchantAuth;
}
function createTransactionRequestObject() {
let transactionRequest = {};
transactionRequest.transactionType = "authCaptureTransaction"
transactionRequest.amount = "20.00"
transactionRequest.profile = {};
transactionRequest.profile.customerProfileId = "123456789"
return transactionRequest;
}
function getHostedPaymentPageRequest() {
let request = {}
request.getHostedPaymentPageRequest = {}
request.getHostedPaymentPageRequest.merchantAuthentication = createMerchantAuthObject();
request.getHostedPaymentPageRequest.transactionRequest = createTransactionRequestObject();
return request; // used in order to print the whole object
}
const myObject = getHostedPaymentPageRequest();
console.log(myObject);
This solved my problem:
var money=document.getElementById("amount").value;
var customerprofileid = "1926616706";
var merchantAuthentication = {};
merchantAuthentication.name = "ser555";
merchantAuthentication.transactionKey = "fgrtyujjj";
var getHostedPaymentPageRequest = {
"getHostedPaymentPageRequest": {
"merchantAuthentication": {
"name": merchantAuthentication.name,
"transactionKey": merchantAuthentication.transactionKey
},
"transactionRequest": {
"transactionType": "authCaptureTransaction",
"amount": money,
"profile": {
"customerProfileId": customerprofileid
}
},
"hostedPaymentSettings": {
"setting": [ {
"settingName": "hostedPaymentIFrameCommunicatorUrl",
"settingValue": "{\"url\": \"http://localhost:52965/IframeCommunicator.html\"}"
}]
}
}
};
getHostedPaymentPageRequest = JSON.stringify(getHostedPaymentPageRequest);
Related
I have data in this format. This is gamesparks data that is BaaS using for game development.
I am sending this data to the IOS person but he said he can not fetch this type of data so he told me to change the data
This is my actual data
{
"Details": [{
"5d4c2c28dcf224127a30457b": {
"displayName": "ewqeqw"
},
"5d4c4699dcf224127a3045e0": {
"displayName": "mmmmmmmmmm"
}
}]
}
and I need to change data in this format
{
"Details": [{
"ID": "5d499b0fdcf224127a303d61",
"displayName": "qweqewq"
},
{
"ID": "5d499b0fdcf224127a303d61",
"displayName": "qweqewq"
}
]
}
This is my code:
var group = Spark.getData().group;
var API = Spark.getGameDataService();
var all1 = new Array();
var entry = API.getItem("playerFriends", Spark.getPlayer().getPlayerId());
var friendsList = {};
if (entry.error()) {
Spark.setScriptError("ERROR", error);
Spark.exit();
} else {
var data = entry.document().getData();
if (group === "all") {
for (var friendOBJ in data) {
//Set details of player ID and display name in new friendsList
object
friendsList[friendOBJ] = {};
friendsList[friendOBJ].displayName = data[friendOBJ].displayName;
friendsList[friendOBJ].playerId = data[friendOBJ].playerId;
}
all1.push(friendsList);
} else {
for (var friendOBJ in data) {
if (data[friendOBJ].group === group && data[friendOBJ].status ===
"accepted") {
friendsList[friendOBJ] = {};
friendsList[friendOBJ].displayName = data[friendOBJ].displayName;
}
}
}
Spark.setScriptData("Details", all1);
Can you not just make a function to convert the data into the desired shape? Something like this should work:
function formatData(details) {
var formattedDetails = [];
for (var id in details) {
formattedDetails.push({
ID: id,
displayName: details[id].displayName
});
}
return formattedDetails;
}
var data = {
"Details": [
{
"5d4c2c28dcf224127a30457b": {
"displayName": "ewqeqw"
},
"5d4c4699dcf224127a3045e0": {
"displayName": "mmmmmmmmmm"
}
}
]
};
var formattedData = formatData(data.Details[0])
this is the output you want
{
"Details": [{
"ID": "5d499b0fdcf224127a303d61",
"displayName": "qweqewq"
}
}
and this is my code i am explaining each line with comment
var count = 0;
var tmp = { AcceptedFriendList: []}; //make object and inside empty array
for (var friendOBJ in data) { // retrieving data
if(data[friendOBJ].status === "accepted"){ // your condition
var tempObj = {"displayName" :"","playerid": ""}; //this is format you want
tempObj.displayName = data[friendOBJ].displayName; // putting data in spicify format object
tempObj.playerid = data[friendOBJ].ID;
tmp.AcceptedFriendList[count] = tempObj; //assign object back to array
count++; // iterate it so the next data come further.
}}
I am trying to link a json object to multiple objects.
$scope.persons = [
{"prename":"Max", "surname":"Shepherd"},
{"prename":"Sarah", "surname":"Shepherd"}
];
$scope.contracts = [
{"contract":"liability", "payment":"8.40"},
{"contract":"health", "payment":"48.12"}
];
// Save new Person
$scope.newPerson = {};
$scope.savePerson = function() {
$scope.persons.push($scope.newPerson);
$scope.newPerson = {};
}
// Save new Contract
$scope.newContract = {};
$scope.saveContract = function() {
$scope.contract.push($scope.newContract);
$scope.newContract = {};
}
How can I save a new Contract and link/nest it to 2 persons.
e.g. the liability contract should be nested to 2 persons.
The health contract should be nested only to 1 person.
But the contract should also be an own object.
The final array should propably look like this:
$scope.persons = [
{
"prename":"Max",
"surname":"Shepherd",
"contracts": {
{"contract":"liability", "payment":"8.40"}
}
},
{
"prename":"Sarah",
"surname":"Shepherd",
"contracts": {
"contract":"liability", "payment":"8.40"
"contract":"health", "payment":"48.12"
}
}
];
$scope.contracts = [
{"contract":"liability", "payment":"8.40"},
{"contract":"health", "payment":"48.12"}
];
you could add a contract id, and then link the id to each person who has the contract.
{"contract":"liability", "payment":"8.40","contractKey":"123"},
{"contract":"health", "payment":"48.12","contractKey":"321"}
$scope.persons = [
{
"prename":"Max",
"surname":"Shepherd",
"contracts": {
"123",
"321"
}
},
{
"prename":"Sarah",
"surname":"Shepherd",
"contracts": {
"123"
}
}
];
Then you would need a function to search for the correct contracts
function findContractForAllPeople(){
angular.forEach($persons,function(key,values){
angular.forEach(values,function(DataKey,val){
angular.forEach($contracts,function(contractKey,contractDetails)
if(DataKey === "contracts"){
if($scope.contracts.contractKey === val){
$scope.finalArray[prename] = {"contracts":contractDetails }
}
})
})
})
}
this will create an object that will look like this
{
Max:{
"contracts":{"contract":"liability", "payment":"8.40","contractKey":"123"},
{"contract":"health", "payment":"48.12","contractKey":"321"}}
},
Sarah:{
{"contract":"liability", "payment":"8.40","contractKey":"123"}
}
I am trying to construct my own JSON object from multiple online image/photography sources. The below code should explain what I am trying to accomplish:
var searchUnsplash = require('./apis/unsplash');
var searchFlickr = require('./apis/flickr');
function combineObjs(callback) {
var obj = {}
var key = 'item';
obj[key] = [];
searchFlickr.searchFlickr(searchTerm, searchCount, searchPage,
function (callback) { // each API call is in a separate file with these functions exported
obj[key].push(flickrObj); // this does not work
// console.log(flickrObj) // this works
});
searchUnsplash.searchUnsplash(searchTerm, searchCount, searchPage,
function (callback) {
obj[key].push(unsplashObj);
// console.log(unsplashObj)
});
console.log(obj)
}
combineObjs();
The goal is to end up with a JSON object like below:
["item": {
"id": 1,
"title": 2,
"content": 3,
"source": "flickr"
},
"item": {
"id": 1,
"title": 2,
"content": 3,
"source": "unsplash"
}]
etc, which I can use to power my front end.
I am a beginner to javascript and I am just working off what I have learned in tutorials and articles, so I might be using the wrong approach entirely for what I am aiming to achieve. Happy to take any pointers
search function:
function searchUnsplash(term, count, page, callback) {
request(`https://api.unsplash.com/search/photos/?per_page=${count}&page=${page}&query="${term}"&client_id=KEY&`,
function searchResult(error, response, body) {
if (!error && response.statusCode == 200) {
var info = JSON.parse(body)
for ( var i = 0; i < info.results.length; i++) {
obj = {
id: `us-${info.results[i].id}`,
}
callback(obj);
}
}
})
}
module.exports.searchUnsplash = searchUnsplash;
First, your intended result is not correct. You can't name "item" the individual array entries. A corrected and working example would be this one.
[ {
"id": 1,
"title": 2,
"content": 3,
"source": "flickr"
},
{
"id": 1,
"title": 2,
"content": 3,
"source": "unsplash"
}]
Second, you mistake JSON for your data structure. JSON is just the text notation. So, let's see first how to build a suitable data array.
let results = [];
results.push( { id:1, title:2, content:3, source:"flickr" });
results.push( { id:2, title:4, content:6, source:"unsplash" });
And then with JSON.stringify(results) will code your results into JSON.
Finally, you mix up the aynchronous calls in your code with synchronous invocations. You need to save the results on the callback of the individual functions, that is when you really obtain the responses asynchronously. Also, you need to count the pending results and invoke the final callback when all done.
So, putting all the pieces together, in a contrived fake example, we just invoke twice the search functions and so we callback when two results are combined.
function combineObjs(callback) {
let results = [];
function partialResult(obj) {
results.push(obj);
if (results.length=2) callback(results);
};
searchFlickr(searchTerm, searchCount, searchPage, partialResult);
searchUnsplash(searchTerm, searchCount, searchPage,partialResult);
}
combineObjs( function(results) { console.log(JSON.stringify(results)) });
This is excessive but it would work. It can be used over and over and over again. :D
Run the snippet to see a result
class JSONBuilder
{
constructor(contents=null)
{
if(!contents)
{
//Private objecy hash that isn't publicly accessible
var objectHash = {};
//Get stashed item
this.GetItem = function(key)
{
if(!key) throw new Error("Null or Underfined Key Passed.");
let value = objectHash[key];
if(!value) throw new Error(`Key : ${key} Not Found in JSON objectHash`);
return value;
}
//Set an item in the objecy hash
this.SetItem = function(key, value)
{
if(!key) throw new Error("Null or Underfined Key Passed.");
if(!value) throw new Error("Null or Underfined Key Not Found.");
objectHash[key] = value;
}
//Remove item from the hash
this.DeleteItem = function(key)
{
if(!key) throw new Error("Null or Underfined Key Passed.");
if(!objectHash[key]) throw new Error(`Key : ${key} Not Found in JSON objectHash`);
objectHash.DeleteItem(key);
}
//Turn items into a JSON object
this.Build = function()
{
return JSON.stringify(objectHash);
}
}
else
{
//If a string is passed as a paremeter, reconstruct from that
try
{
objectHash = JSON.parse(contents);
}
catch(Err)
{
console.log("Parsing of JSON Content Failed.");
throw Err;
}
}
}
}
class Item
{
constructor(id, source, content, title)
{
this.Id = id;
this.Source = source;
this.Content = content;
this.Title = title;
}
}
let builder = new JSONBuilder();
let itemContainer = [];
itemContainer.push(new Item(1, 'flicker', 'stuff', 'item1'));
itemContainer.push(new Item(2, 'flicker', 'morestuff', 'item2'));
builder.SetItem('items', itemContainer);
console.log(builder.Build());
I have data in the form of
data = [
{
"date":"2018-05-18T-6:00:00.000Z",
"something":"something1",
"something":"something1"
},
{
"date":"2018-05-19T-6:00:00.000Z",
"something":"something2",
"something":"something2"
}
]
How do I grab the first element in the objects, edit them, then replace them back in the object?
So it should look like this
data = [
{
"date":"2018-05-18",
"something":"something1",
"something":"something1"
}
{
"date":"2018-05-19",
"something":"something2",
"something":"something2"
}
]
I have tried something like this
var date = [];
const getSessions = () => {
loginService.getUser().then((response) => {
var user_id = response.data.id;
console.log("getUser returning this => ", response.data);
loginService.getUserSessions(user_id).then((response) => {
$scope.sessions = response.data;
for (var i = 0; i < $scope.sessions.length; i++){
date.push($scope.sessions[i].next_class.slice(0,10));
};
$scope.sessions.push(date);
console.log($scope.sessions);
This gets the date shortened but doesn't replace the original date in the object.
You can do something like -
var data = [
{
"date":"2018-05-18T-6:00:00.000Z",
"something":"something1",
},
{
"date":"2018-05-19T-6:00:00.000Z",
"something":"something2"
}
]
data.forEach((record) => {
record.date = record.date.split("T")[0]
})
console.log(data);
You can do this also.
`
newArray = data.map(obj => {
dateIntoString = moment(obj.date).format('YYYY-MM-DD');
obj.date = dateIntoString;
return obj;
});
`
I want to create new array by json data But I have no idea to create Object!
for show to page(loop for)
my json data
"LIBRARIES":{
"LIBRARY":[
{
"status":"available",
"callNumber":"123456"
},
{
"status":"available",
"callNumber":"434356"
}
]
}
and
"search":{
"lsr02":[
"31011103618567",
"31011001644160"
]}
I want to create object to store this data
I want
"NEWDATA":{
"NEW":[
{
"status":"available",
"callNumber":"123456",
"lsr02": "31011103618567" ///set lsr02 to store in NEW
},
{
"status":"available",
"callNumber":"434356"
"lsr02":"31011001644160"
}
]
}
and I try
let details: string[] = [];
for (let x of this.item.LIBRARIES.LIBRARY){
details.push(x);
}
for (let x of this.item.search.lsr02){
details.push(x);
}
console.log(details)
console.log(details) show
{
"status":"available",
"callNumber":"123456"
},
{
"status":"available",
"callNumber":"434356"
}
{
"31011103618567"
},
{
"31011001644160"
}
thanks for your help :)
You are pushing the search objects separately. You need to assign them to appropriate library object. Try this;
this.item = {
"LIBRARIES": {
"LIBRARY": [{
"status": "available",
"callNumber": "123456"
},
{
"status": "available",
"callNumber": "434356"
}
]
},
"search": {
"lsr02": [
"31011103618567",
"31011001644160"
]
}
}
let details = [];
for (let i = 0; i < this.item.LIBRARIES.LIBRARY.length; i++) {
let lib = this.item.LIBRARIES.LIBRARY[i];
lib.lsr02 = this.item.search.lsr02[i]
details.push(lib);
}
console.log(details)
export class NEWDATA {
public status:string;
public callNumber:string;
public lsr02 : string;
constractor(_status : string, _callNumber : string, _lsr02 : string){
this.status = _status;
this.callNumber = _callNumber;
this.lsr02 = _lsr02;
}
}
details : Array<NEWDATA> = [];
for (let i = 0; i < this.item.LIBRARIES.LIBRARY.length; i++) {
details.push(new NEWDATA(this.item.LIBRARIES.LIBRARY[i].status, this.item.LIBRARIES.LIBRARY[i].callNumber, this.item.search.lsr02[i]));
}