In Logic Apps I have this function which replaces double double quotes with a zero for some strings.
How can I replicate this in Javascript?
replace(replace(replace(replace(replace(body('HTTP_2'),'"PR_RENT":""','"PR_RENT":0'),'"PR_ID":""','"PR_ID":0'),'"PR_USUM":""','"PR_USUM":0'),'"PR_LEAS":""','"PR_LEAS":0'),'"PR_USER8":""','"PR_USER8":0')
I tried this code.
```
var json = workflowContext.actions.HTTP_2.outputs.body
if (json.PR_RENT=="\"\"")
{
json.PR_RENT=0
}
if (json.PR_ID=="\"\"")
{
json.PR_ID=0
}
if (json.PR_USUM=="\"\"")
{
json.PR_USUM=0
}
if (json.PR_LEAS=="\"\"")
{
json.PR_LEAS=0
}
if (json.PR_USER8=="\"\"")
{
json.PR_USER8=0
}
return json;
```
and got error messages like this for all the affected fields.
```[
{
"message": "Invalid type. Expected Integer but got String.",
"lineNumber": 0,
"linePosition": 0,
"path": "Payload[0].PR_USER8",
"value": "",
"schemaId": "#/properties/Payload/items/properties/PR_USER8",
"errorType": "type",
"childErrors": []
},
,
{
"message": "Invalid type. Expected Integer but got String.",
"lineNumber": 0,
"linePosition": 0,
"path": "Payload[2].PR_RENT",
"value": "",
"schemaId": "#/properties/Payload/items/properties/PR_RENT",
"errorType": "type",
"childErrors": []
}
]
Here is some of my JSON code
```{"Payload":[{"RLS_GROUP":"","PR_SNAM":"700063","PR_OWN":"qqq","PR_REF":"","PR_NAME":"Bqqq12","PR_ADD1":"qqq","PR_ADD2":"INDUSTRIAL ESTATE","PR_ADD3":"23 INDUSTRIAL ESTATE","PR_ADD4":"yyy","PR_ADD5":"","PR_ADD6":"GB","PR_POST":"WQDQWD","PR_TEL":"23213","PR_TELX":"21312312","PR_FAX":"","PR_CONT":"","PR_NUNIT":"","PR_INT":"","PR_TENR":"LEASED","PR_QDAY":"","PR_CLSS":"","PR_DRCT":"Closing","PR_AGENT":"","PR_NOWN":"","PR_BOWN":"","PR_SOL":"","PR_HSTT":"","PR_HEND":"","PR_HAMT":"","PR_PFREQ":"","PR_NTENT":"","PR_NFLR":"","PR_GRA":"","PR_WATER":"","PR_RATVAL":"","PR_RTCT":"","PR_SCHG":"","PR_OCHG":"","PR_GFA":"","PR_ZONEA":"","PR_ZONEB":"","PR_ZONEC":"","PR_UPDATE":"","PR_UTIME":"","PR_UUSER":"","PR_HIST":"","PR_TAXYN":"","PR_TAX":"","PR_START":"","PR_END":"","PR_FREQ":"","PR_QTR":"","PR_NDUE":"","PR_TAXRUN":"","PR_OUTLET":"","PR_INLET":"","PR_VAL":"","PR_CST":"","PR_FRWA":"","PR_FRWB":"","PR_PRINT":"","PR_NL":"","PR_CURRS":"","PR_NEXTS":"","PR_VAT":"D","PR_USER":"","PR_VQDAY":"","PR_OBS1":"STANDARD NORTH","PR_TYPE":"Property","PR_VATDATE":"","PR_FUTHER":"","PR_RESTEN":"","PR_CAPGOODS":"","PR_INSEE":"","PR_CURR":"","PR_AQDATE":"20190917","PR_USER1":"Office","PR_USER2":"Yes","PR_USER3":"","PR_USER4":"","PR_USER5":"20190917","PR_USER6":"","PR_USER7":"","PR_USER8":0,"PR_USER9":"","PR_USER10":"","PR_OBS2":"","PR_OBS3":"","PR_OBS4":"","PR_OBS5":"","PR_OBS6":"","PR_OBS7":"UK","PR_OBS8":"","PR_OBS9":"","PR_SOLD":"0","PR_DATESOLD":"20200917","PR_LAND":"","PR_LANDUM":"","PR_FREE":"","PR_ID":0,"PR_BTYP":"F","PR_LEAS":0,"PR_RENT":999999,"PR_USUM":0,"PR_FBUI":0,"PR_DREN":"","PR_USRC":"","PR_RSRC":"","PR_LSRC":"","PR_ELSR":"","PR_EGRS":"","PR_PROR":"","PR_BSTA":"","PR_LNAM":"123123213","PR_SITE":"","PR_REGION":"","PR_DESC":""}]}
I have to do this because the API is returning "" for integer fields instead of zero when there is no value.
I tried this code
var json = workflowContext.actions.HTTP_2.outputs.body;
json.Payload[0].RLS_GROUP='Test';
json.Payload[0].PR_REF=123;
return json;
and got this message
InlineCodeScriptRuntimeFailure. The inline code action 'JavaScriptCode'
execution failed, with error 'Cannot read property '0' of undefined'.
Also, my Javascript action screen looks a bit different to yours.
I tried this code. It seems to have worked for the first example, but not all examples. Perhaps the data contains a space before the double double quotes.
How do I iterate through all payload elements?
var jsonString = workflowContext.actions.HTTP_2.outputs.body;
const json =JSON.parse(jsonString);
const dic = json['Payload'][0];
const checkFields = ['PR_RENT','PR_ID','PR_USUM','PR_LEAS','PR_USER8'];
checkFields.forEach(field=>{
console.log(dic[field]);
if(dic[field]=='""')
{
dic[field]=0;
console.log(field);
}
}
);
return json;
If you want to use JavaScript to manage the json, just set the value directly. You could refer to my actions as the below pic show. The expression would be like json.key=value;
Update: I test with the array json it could work, you need to point the index. If not please provide more information.
This treats the json as a string and not an array.
json=json.replace(/"PR_USER8":""/g,'"PR_USER8":0').replace(/"PR_RENT":""/g,'"PR_RENT":0').replace(/"PR_ID":""/g,'"PR_ID":0').replace(/"PR_USUM":""/g,'"PR_USUM":0').replace(/"PR_LEAS":""/g,'"PR_LEAS":0');
return json;```
I think this is better as it treats the json as an object not a string.
```
var jsonString = workflowContext.actions.HTTP_2.outputs.body;
const json =JSON.parse(jsonString);
const ret =[];
const dic = json['Payload'];
const checkFields = ['PR_RENT','PR_ID','PR_USUM','PR_LEAS','PR_USER8'];
for(i in json['Payload'])
{
checkFields.forEach(field=>{
if(json.Payload[i][field]=="")
{
json.Payload[i][field]=0;
// console.log(field);
}
}
);
}
return json;
```
I'm trying to load some JSON data from a JSON file and carrying out some data manipulation on it for an app I'm trying to build. However, when looping through the data, I'm getting an undefined error which makes it seem that property is missing from the JSON object when I use a looping variable to access the objects. However, when I index the JSON array with a hardcoded number, the property loads fine. I am wondering if someone can help me out with this. I've attached an example of the code and the JSON to this.
I have tried stringifying the JSON and parsing it again and tried both accessing the JSON using square brackets as well as the full stop and they all lead to the same result.
Code to access:
import ontology from '../../data/ontology.json'
const totalAnswerList = ontology.answers
for (var i = 0; i <= totalAnswerList.length; i++) {
var wordID = totalAnswerList[i] // wordID.id returns undefined
var wordID2 = totalAnswerList[0] // wordID2.id works
alert(JSON.stringify(wordID) + JSON.stringify(wordID2) + '\nWord ID hardcoded: ' + wordID2.id)
}
//ontology.json
{
"answers": [
{
"id": "examination",
"category_id": "examination",
"synonyms": ["examination"]
}, ...
], ...
}
The code you provided works as expected, but the issue is the last element is undefined because of your for loop constraints. You likely want i < totalAnswerList.length and not <=. Because if the array is 5 elements long, you want to loop through 0,1,2,3,4 (and not 5, which will be undefined).
import ontology from "./ontology.json";
const totalAnswerList = ontology.answers;
for (var i = 0; i < totalAnswerList.length; i++) {
// ...
}
I'm getting a bad response when i post a json.stringify via fetch, and the problem is from escaped quotes that json.stringify is producing. It works when I remove them manually, but I need this to be done automatically.
var order = {
"from_country": "US",
"line_items": [
{
"quantity": 1,
"unit_price": 19.95
}
],
"to_country": "US"
};
var body = JSON.stringify(order);
var body will display as:
{"from_country":"US","line_items":"[{\"quantity\": 1, \"unit_price\": 19.95}]","to_country":"US"}
I'd like it to display as:
{"from_country":"US","line_items":"[{"quantity": 1, "unit_price": 19.95}]","to_country":"US"}
The issue was that my file includes the prototype library.
I fixed the conflict, while still maintaining the functionality(I think) of prototype by adding this code -
JSON = JSON || {};
JSON.stringify = function(value) { return Object.toJSON(value); };
JSON.parse = JSON.parse || function(jsonsring) { return jsonsring.evalJSON(true); };
I first stumbled on this being the problem here:https://stackoverflow.com/a/20331694/8326722
which led me to https://stackoverflow.com/a/1327371/8326722 and then I added the bit from a comment to get it to work with objects.
If someone can explain how the code I'm using works, that would be nice.
I have a casperjs script which iterates over a list of pages and extracts data.
On the other hand I have a csv file with 2 fields 'ean' 'ref' which I parse with Papa.parse. The output is an object. I am looking for a solution to query an javascript object (the output from Papa.parse) for the 'ref' field and extract the 'ean'. I thought .filter() is what i was looking for but that can only search for a predefined value in the callback function.
function cd(element) {
return element == '123';
}
var b = c.filter(cd);
The problem hear is 1. It returns an empty array and 2. even if it would work I need to change the value with every call since I want to find the ean value for any given ref.
function cd(element,ref) {
return element == ref;
}
This is the data I need to search
"data": [
{
"ean": "654321",
"ref": "123"
},
{
"ean": "1234567",
"ref": "124"
}
]
I hope I made myself more clear. Thank you in advance
I used https://lodash.com/docs#where
Does exactly what i want
var a = _.where(array,{'ref' : 'value i am looking for'});
result is an array from where I can extract the value of the ean field.
Given a JSON string as this:
{
"__ENTITIES": [
{
"__KEY": "196",
"__STAMP": 1,
"ID": 196,
"firstName": "a",
"middleName": "b",
"lastName": "c",
"ContactType": {},
"addressCollection": {
"__deferred": {
"uri": "/rest/Contact(196)/addressCollection?$expand=addressCollection"
}
},
"__ERROR": [
{
"message": "Cannot save related entity of attribute \"ContactType\" for the entity of datastore class \"Contact\"",
"componentSignature": "dbmg",
"errCode": 1537
}
]
}
]
}
Is there a method to get just the __ERROR record, I know I can use
var mydata = json.parse(mydata) and then find it from the mydata object. But I was hoping there was a method to only return the ERROR field something like
json.parse(mydata, "__ERROR") and that gets only the information in the __ERROR field without turning the whole JSON string into an object
"Is there a method to get just the __ERROR record, I know I can use var mydata = json.parse(mydata) ... But I was hoping there was ... something like json.parse(mydata, "__ERROR")"
There may be libraries that do this, but nothing built in. You need to write code that targets the data you want.
The closest you'll get will be to pass a reviver function to JSON.parse.
var errors = [];
var mydata = JSON.parse(mydata, function(key, val) {
if (key === "__ERROR")
errors.push(val);
return val
});
without turning the whole json string into an object
That's hardly possible, you would need some kind of lazy evaluation for that which is not suitable with JS. Also, you would need to write your own parser for that which would be reasonable slower than native JSON.parse.
Is there a method to get just the __ERROR record
Not that I know. Also, this is an unusual task to walk the whole object tree looking for the first property with that name. Better access __ENTITIES[0].__ERROR[0] explicitly.
If such a function existed, it would have to parse the whole thing anyway, to find the key you're looking for.
Just parse it first, then get the key you want:
var mydata = JSON.parse(mydata);
var errorObj = mydata.__ENTITIES[0].__ERROR[0];
If you want, you may create your own function:
function parseAndExtract(json, key) {
var parsed = JSON.parse(json);
return parsed[key];
}