Create Dymanic JSON string using only Javascript - javascript

I am working with the Code Canyon script Spin2Win (https://codecanyon.net/item/spin2win-wheel-spin-it-2-win-it/16337656), which uses a local JSON file to create the segments.
The part of the JSON file that control the segments has the following format.
"segmentValuesArray" : [
{"probability":10, "type": "string", "value": "$10^Coupon", "win": true, "resultText": "You won a $10 Coupon", "userData": {"score":0}},
{"probability":30, "type": "string", "value": "Lose", "win": false, "resultText": "Thank you for Playing", "userData": {"score":0}},
{"probability":5, "type": "string", "value": "$25^Coupon", "win": true, "resultText": "You won a $25 Coupon", "userData": {"score":0}},
{"probability":30, "type": "string", "value": "Lose", "win": false, "resultText": "Thank you for Playing", "userData": {"score":0}},
{"probability":2, "type": "string", "value": "Free Spin", "win": true, "resultText": "You Won a Free Spin", "userData": {"score":0}},
{"probability":30, "type": "string", "value": "Lose", "win": false, "resultText": "Thank you for Playing", "userData": {"score":0}},
{"probability":3, "type": "string", "value": "SWAG", "win": true, "resultText": "You won SWAG", "userData": {"score":0}},
{"probability":30, "type": "string", "value": "Lose", "win": false, "resultText": "Thank you for Playing", "userData": {"score":0}},
{"probability":1, "type": "string", "value": "GOOGLE^Home", "win": true, "resultText": "You won a Google Home", "userData": {"score":0}}
],
My issues is I have a $50 and $100 coupon as well that will have lower probability values. But I only ever want 2 coupons on the wheel at any given time. So my thought was to pick a coupon value at random and then use a find and replace to update to the two coupon segements before the spin script processes the json.
I have tested and I can add an ID tag to the segmentValueArrary such as follows:
{"id":"01", "probability":10, "type": "string", "value": "$10^Coupon", "win": true, "resultText": "You won a $10 Hosting Coupon", "userData": {"score":0}},
I have found this answer: JSON Object array inside array find and replace in javascript
But it only gives an example of how to replace one value and I need to replace the probability, value and the resultText Any attempts to modify the code find and replace code has failed.
***** UPDATE #1 *****
I have played around with a little bit of code and gotten to work in Jsfiddle. (http://jsfiddle.net/6347s9bo/)
The issues I am running into now is how the developer loads and processes the JSON. Here is his code
loadJSON(function(response) {
// Parse JSON string to an object
var jsonData = JSON.parse(response);
........
And here is his loadJSON function
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', './wheel_data.json', true);
xobj.onreadystatechange = function() {
if (xobj.readyState == 4 && xobj.status == "200") {
//Call the anonymous function (callback) passing in the response
callback(xobj.responseText);
}
};
xobj.send(null);
}
The error I am getting now is object.map is not a function. I am placing my findAndReplace() call after his JSON.parse call, which should turn the text into an object.
Not sure what I am missing

you could try this:
function changeAttributes(objArray, objId, probability, value, resultText) {
objArray.forEach(function(obj) {
if (obj.id === objId) {
obj.probability= probability;
obj.value = value;
obj.resultText = resultText;
}
});
}
The objId is the Id of the object in the Array you want to replace.
The 3 values are the new values you want to set.
You have to call the method 2 times, one time for every coupon to replace the attribuites.

Not sure to understand your question exactly. JSON is basically a javascript array. So updating it do not require to convert it to a string. Finding a value in an array is pretty simple. In your case, simply create a function like this :
function isCoupon(item) {
return item.id === '01';
}
then search it like this :
arrayItem = segmentValuesArray.find(isCoupon);
arrayItem.value.replace('10^','100^');

So I would iterate over the list and mutate the coupons accordingly. You will have to add extra logic to handle selecting which coupon at random you are selecting but I think this gives a place to start.
segmentValuesArray.forEach(segment => {
if (segment.value.includes("Coupon")) {
segment.probability = 0;
segment.resultText = '';
}
});
reference on includes:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
reference on forEach:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

Related

How can we access the Child Key from Object

I'm trying to loop my child array but it's not working. It's working fine which it's first items but not working on the child elements.
"candidateApplication": [
{
"label": "Are you currently attending school?",
"id": "ap_currentschool",
"value": "",
"required": "N",
"type": "radio",
"display": null,
"list": [
{
"searchCode": "yes",
"searchValue": "yes"
},
{
"searchCode": "no",
"searchValue": "no"
}
],
"onSelect": [
{
"yes": [
{
"label": "Estimated Completion Date",
"id": "ap_compdate",
"value": "",
"required": "N",
"type": "date",
"display": null,
"list": null,
"onSelect": null
}
],
"no": null
}
]
},
]
I am easily access my data to looping lists like obj.candidateApplication.list But I am not able to loop through obj.candidateApplication.onSelect.yes.
Can anybody please guide me how can I fix that issue.
enter image description here
You are accessing obj.candidateApplication.onSelect.yes which is undefined because obj.candidateApplication.onSelect is an array of objects.
You probably want to loop over obj.candidateApplication.onSelect and then for each object you can access the yes property as you wish:
$.each(onSelect, function (index, element) {
$.each(element.yes, function (x, y) {
// your code here
})
});
Edit: As pointed by Heritic Monkey in the comments, obj.candidateApplication is an array as well, but in the picture attached to the question, there's already a local variable called onSelect, loop through that instead of obj.candidateApplication.onSelect because it's undefined. (at least it should be, we don't know what your code is doing)

Passing JSON created in PHP to Javascript changes a result and I don't understand why

I have an object in PHP that I'm passing to Javascript in the same page. It seems to be passing through fine as a console.log statement returns the expected result but when I try to turn it into a Javascript variable the "id" is replaced with a 1, no quotation marks, rather than the expected result. If I wrap the PHP statement in the Javascript in square brackets the "id" does not change, but then it's formatted oddly. What I'm wondering is why this is occurring and if there's something I should do differently.
ETA:
Since there was some confusion:
The input is "Data," below. That is generated from the results of a SQL query by way of an array_push statement. I have included the code for each row of the SQL query and the array_push statement below, but there does not seem to be a problem with the PHP side.
My expected output is simply the data to be transferred to a JSON object on the javascript side with the appropriate variable, using the code mentioned under "Javascript." Instead I am getting something like this as console.log output:
{
DNB_number: "0"
color: "darkred"
id: 1
name: "Anonymous"
role: "Author"
size: null
type: "person"
witness_work_id: "1467"
witness_work_role_id: "1659"
}
That 1 under id is what is the issue.
There is nothing happening on the javascript side before the attempt to convert the result to a javascript variable (what you see under javascript below), so there's not much else I can tell you there. The conversion on the PHP side happens, I start my javascript, then immediately attempt to invoke it on the javascript side.
PHP code:
$person_color = "darkred";
foreach ($person_data as $row) {
$person_id = $row["person_id"];
$type = "person";
$witness_work_role_id = $row["Witness_work_role_id"];
$witness_work_id = $row["Witness_work_id"];
$person = $row["Person_name"];
$DNB = $row["Oxford_DNB_number"];
$role = $row["Role"];
$color = $person_color;
array_push($GLOBALS['person_array'], array(
'id'=>$person_id,
'witness_work_role_id'=>$witness_work_role_id,
'witness_work_id'=>$witness_work_id,
'type'=>$type,
'name'=>$person,
'DNB_number'=>$DNB,
'role'=>$role,
'color'=>$color,
'size'=> NULL
));
}
$jperson = json_encode($person_array);
Javascript code:
person_array = <?=$jperson; ?>;
Data:
[
{
"id": "1",
"witness_work_role_id": "1660",
"witness_work_id": "1468",
"type": "person",
"name": "Anonymous",
"DNB_number": "0",
"role": "Author",
"color": "darkred",
"size": null
},
{
"id": "152",
"witness_work_role_id": "1573",
"witness_work_id": "1384",
"type": "person",
"name": "Gilbert Banester",
"DNB_number": "0",
"role": "Author",
"color": "darkred",
"size": null
},
{
"id": "153",
"witness_work_role_id": "1574",
"witness_work_id": "1385",
"type": "person",
"name": "Elizabeth Plantagenet (Elizabeth of York)",
"DNB_number": "8635",
"role": "Author",
"color": "darkred",
"size": null
},
{
"id": "3",
"witness_work_role_id": "1642",
"witness_work_id": "1451",
"type": "person",
"name": "Geoffrey Chaucer",
"DNB_number": "5191",
"role": "Author",
"color": "darkred",
"size": null
},
{
"id": "7",
"witness_work_role_id": "1643",
"witness_work_id": "975",
"type": "person",
"name": "Benedict Burgh",
"DNB_number": "3390",
"role": "Author",
"color": "darkred",
"size": null
},
{
"id": "5",
"witness_work_role_id": "1659",
"witness_work_id": "1467",
"type": "person",
"name": "Anonymous",
"DNB_number": "0",
"role": "Author",
"color": "darkred",
"size": null
}
]
Let's work this out in a minimal example. Based on what you're saying, the variable is a string (of an int), and the value is correct in memory. But when you view that value via console.log you see an int instead of a string.
var test = "1";
if (typeof test == 'string') {
console.log('yes, it is a string');
} else {
console.log('no, it is not a string');
}
If you copy/paste the above into your JS console and run it, you'll see the message yes, it is a string. This proves that it is a string in memory.
another way to test this value is to just run test in your console, and you should see "1" output.
But now, when we use console.log to inspect the value:
console.log(test) outputs 1
Another example without a variable: console.log("123") outputs 123, not "123"
What's apparently happening is just an artifact of console.log. See Javascript console.log(object) vs. concatenating string for more examples and explanations. https://dmitripavlutin.com/console-log-tips/ lists some more options. For instance, if you create an object containing your variable and output that: console.log({test}) will output {test: "1"}, so you can see again that test is a string with the value "1".

Error in enum data type while uploading intent dialogflow

I am trying to upload my intent everything is working fine, i am writing script in V2 and everything works but for parameter webhookState data type is enum ( [here] ) and we have to enter following of the three values ( [here][1]) now when i enter any one and try to upload it shows.
" Unable to load file: SyntaxError: Unexpected token W in JSON at position 98 "
now when I pass WEBHOOK_STATE_ENABLED(or any one) in quotes code uploads successfully (because as per my knowledge it treats it as string and gets executed) and intent is created for my agent but webhook remains off and also training phrases are not there, i am certain that the parameter webhookState is not being activated when i pass in quotes(because of above mentioned reason) Same is the case with rest, like when i try to put in type of training phrases.
{
"name": "Warehouse_Management",
"displayName": "Warehouse_Management",
"webhookState": "WEBHOOK_STATE_ENABLED_FOR_SLOT_FILLING" ,
"priority": 50000,
"isFallback": false,
"mlDisabled": false,
"trainingPhrases": [
{
"name":"Try1" ,
"type": "EXAMPLE",
"parts": [
{
"text": "for",
"userDefined": true
},
{
"text": "warehouse",
"entityType": "#Properties",
"alias": "Properties",
"userDefined": true
},
{
"text": "management",
"userDefined": true
}
]
},
{
"name":"Try2" ,
"type": "EXAMPLE",
"parts": [
{
"text": "i want app for ",
"userDefined": true
},
{
"text": "warehouse",
"alias": "Properties",
"entityType": "#Properties",
"userDefined": true
}
]
}
],
"outputContexts": [
{
"name": "Yes",
"lifespanCount": 2
},
{
"name": "No",
"lifespanCount": 2
},
{
"name": "Device_Integration",
"lifespanCount": 2
}
],
"resetContexts": false,
"parameters": [
{
"name": "Properties",
"displayName": "Properties",
"value": "$parameter_name",
"entityTypeDisplayName": "#Properties",
"mandatory": false,
"isList": true
}
],
"messages": [
{
"text":"This is sample response"
}
],
"rootFollowupIntentName": "root",
"parentFollowupIntentName": "parent"
}
Please NOTE that in the attached Json i have put it in quotes so it would get successfully executed and will create intent.
In order for it to be valid JSON, the enum value should be wrapped in quotes. It's expecting the enum value as a String.

Postman: Wanted to validate data values getting from API in JSON format

I wanted to check some combinations of validations for values I am getting from API request in postmanlike
if "tracked": "Yes" then analytics > "transitTime": 239 should be present.
The snippet of API response:
{
"status": 200,
"data": [{
"id": 107267,
"branchId": "22",
"status": "1",
"googleETA": "2018-02-01 20:44:51",
"runDate": "2018-01-29",
"runOfTheDay": "1",
"ATD": "2018-01-29 14:02",
"simCarrier": "Vodafone",
"pingStatus": "Ok",
"driverName": "test",
"shipperCompanyId": "007",
"ETA": "2018-01-30 12:31:00",
"locationSource": "sim",
"created_at": "2018-01-29 07:05:54",
"updated_at": "2018-01-29 12:35:40",
"tracked": "Yes",
"analytics": {
"loadingTime": 55.62,
"unloadingTime": 0,
"transitTime": 239
},
"trackingStatusAtClosure": {
"Origin": "No",
"Transit": "No",
"Destination": "No"
}
}]
}
This is a very basic check and I would advise against using it anywhere other than practising in a local environment.
pm.test("Basic Check", () => {
var jsonData = pm.response.json().data
for(i = 0; i < jsonData.length; i++) {
if(jsonData[i].tracked === 'Yes') {
pm.expect(jsonData[i].analytics.transitTime).to.not.be.null
} else {
console.log('Tracked does not equal Yes')
}
}
})
As your data only has one item in the data array you don't really need to add the for loop but I added it in for you so you can see that the same check would run if you have more than one item. If the tracked property is 'Yes' then the test is checking if analytics.transitTime not null. Like I said, its a basic check and it's not doing a great deal but hopefully that will give you the information you need to get started.

Dialogflow html/js card json value v1

I am trying to access the card json value, to no avail.
In my scenario, I am asking the bot about "weather in London" and it replies back with "It is currently 9 degrees celcius in London." via the webhook.
Which is correct and dynamic.
However, I am trying to also pass the values to a card too.
In the json reply, I do get the card as so
{
"id": "REMOVED",
"timestamp": "2017-12-05T11:10:52.033Z",
"lang": "en",
"result": {
"source": "agent",
"resolvedQuery": "weather in london",
"action": "sayWeather",
"actionIncomplete": false,
"parameters": {
"geo-city": "London"
},
"contexts": [],
"metadata": {
"intentId": "REMOVED",
"webhookUsed": "true",
"webhookForSlotFillingUsed": "false",
"webhookResponseTime": 626,
"intentName": "Weather"
},
"fulfillment": {
"speech": "It is currently 9 degrees celcius in London.",
"source": "agent",
"displayText": "It is currently 9 degrees celcius in London.",
"messages": [
{
"type": 0,
"speech": "It is currently 9 degrees celcius in London."
}
],
"data": {
"items": [
{
"simpleResponse": {
"textToSpeech": "This is the first simple response for a basic card"
}
},
{
"basicCard": {
"title": "Title: this is a title",
"formattedText": "This is a basic card. Text in a\n basic card can include \"quotes\" and most other unicode characters\n including emoji 📱. Basic cards also support some markdown\n formatting like *emphasis* or _italics_, **strong** or __bold__,\n and ***bold itallic*** or ___strong emphasis___ as well as other things\n like line \nbreaks",
"subtitle": "This is a subtitle",
"image": {
"url": "https://developers.google.com/actions/images/badges/XPM_BADGING_GoogleAssistant_VER.png",
"accessibilityText": "Image alternate text"
},
"buttons": [
{
"title": "This is a button",
"openUrlAction": {
"url": "https://assistant.google.com/"
}
}
]
}
},
{
"simpleResponse": {
"textToSpeech": "This is the 2nd simple response ",
"displayText": "This is the 2nd simple response"
}
}
]
}
},
"score": 1
},
"status": {
"code": 200,
"errorType": "success",
"webhookTimedOut": false
},
"sessionId": "REMOVED"
}
Accessing the value of speech using data.result.fulfillment.speech works fine.
However, when using data.result.fulfillment.data.items.basicCard.image.url it just doesnt work. And if I go up several levels, I do get:
[object Object]
Your help is appreciated.
The items attribute is a list and not an object. As such, you'll have to use a numerical index to retrive the data. In the example you provided the index of the basicCard object is second so your code should look something like this:
data.result.fulfillment.data.items[1].basicCard.image.url
Notice the [1] after items.
Bear in mind that if the order of this list changes you may no longer be retrieving a basicCard object so you may want to add some checking to make sure you're retrieving the data you want.

Categories