unable to replace a part of json value using fs javascript - javascript

this is my js code
let content019 = JSON.parse(require("fs").readFileSync("./settings.json"));
// edit or add property
content019.api.client.locations[1] = 999999999999;
//write file
fs.writeFileSync('settings.json', JSON.stringify(content019,null ,2));
i tried using content019.api.client.locations[1] but it changed the inner part to "1": "999....
this is a part of my json file
"1": {
"name": "Germany",
"type": null
},
"2": {
"name": "Singapore",
"type": null
}
},
i want it to only change "1": { to "999999999999": {
even tried content019.api.client.locations.1, didnt work. received error unexpected number

you have to use a string, not a number index. Since your json is invalid, I can only assume that the first part is ok, so you can try
content019.api.client.locations["1"] = 999999999999;
or maybe
content019.api.client.locations["999999"] = content019.api.client.locations["1"];
delete content019.api.client.locations["1"];

Related

How to convert Excel Table to specific JSON format using Office Scripts

I'm trying to get a specific JSON output from Office Scripts in order to make an API call with Power Automate. The output I'm receiving from Power Automate does not have the format required in the API docs (link to API docs below). Tried modifying the script to get the required output but unfortunately, I'm just starting out with js, so I can't figure out what I need.
Right now, the input must come from an Excel table. I can format the excel table differently for this flow if it's needed, but nevertheless, the input must come from an Excel table. Right now, the Excel table looks like this:
This is the Office Script I am using, comes from this blog post: https://learn.microsoft.com/en-us/office/dev/scripts/resources/samples/get-table-data:
function main(workbook: ExcelScript.Workbook): TableData[] {
// Get the first table in the "WithHyperLink" worksheet.
// If you know the table name, use `workbook.getTable('TableName')` instead.
const table = workbook.getWorksheet('WithHyperLink').getTables()[0];
// Get all the values from the table as text.
const range = table.getRange();
// Create an array of JSON objects that match the row structure.
let returnObjects: TableData[] = [];
if (table.getRowCount() > 0) {
returnObjects = returnObjectFromValues(range);
}
// Log the information and return it for a Power Automate flow.
console.log(JSON.stringify(returnObjects));
return returnObjects
}
function returnObjectFromValues(range: ExcelScript.Range): TableData[] {
let values = range.getTexts();
let objectArray : TableData[] = [];
let objectKeys: string[] = [];
for (let i = 0; i < values.length; i++) {
if (i === 0) {
objectKeys = values[i]
continue;
}
let object = {}
for (let j = 0; j < values[i].length; j++) {
// For the 4th column (0 index), extract the hyperlink and use that instead of text.
if (j === 4) {
object[objectKeys[j]] = range.getCell(i, j).getHyperlink().address;
} else {
object[objectKeys[j]] = values[i][j];
}
}
objectArray.push(object as TableData);
}
return objectArray;
}
interface TableData {
"Event ID": string
Date: string
Location: string
Capacity: string
"Search link": string
Speakers: string
}
And this is the output I am getting in Power Automate when I run the Office Script:
[
{
"Line": "",
"Id": "0",
"Description": "nov portion of rider insurance",
"Amount": "100",
"DetailType": "JournalEntryLineDetail",
"JournalEntryLineDetail": "",
"PostingType": "Debit",
"AccountRef": "",
"value": "39",
"name": "Opening Bal Equity"
},
{
"Line": "",
"Id": "",
"Description": "nov portion of rider insurance",
"Amount": "100",
"DetailType": "JournalEntryLineDetail",
"JournalEntryLineDetail": "",
"PostingType": "Credit",
"AccountRef": "",
"value": "44",
"name": "Notes Payable"
}
]
BUT, the schema I need looks like this (it is based on this API doc https://developer.intuit.com/app/developer/qbo/docs/api/accounting/all-entities/journalentry):
{
"Line": [
{
"Id": "0",
"Description": "nov portion of rider insurance",
"Amount": 100.0,
"DetailType": "JournalEntryLineDetail",
"JournalEntryLineDetail": {
"PostingType": "Debit",
"AccountRef": {
"value": "39",
"name": "Opening Bal Equity"
}
}
},
{
"Description": "nov portion of rider insurance",
"Amount": 100.0,
"DetailType": "JournalEntryLineDetail",
"JournalEntryLineDetail": {
"PostingType": "Credit",
"AccountRef": {
"value": "44",
"name": "Notes Payable"
}
}
}
]
}
There are a lot of differences and obviously, when I try to make the API call, I get a 400 'Bad request' error. Does anyone know how I must modify either the Script or the Excel table or do something different in Power Automate in order to get the specific schema I need?
Any help will be appreciated. Thanks!!
I think the core of what's going on is that your script is parsing everything to match a linear "TableData" interface given in the tutorial you followed before it sends it to the Stringify method, but your data doesn't match that interface, so it does the best it can and outputs each individual row into an object array. When Stringify gets called, it sees an array of plain objects, so it just converts everything to a string.
I think you want this to be a bit more structured, which means you'll want to hand-code the objects you're passing for each of your rows. Basically, what your JSON schema is telling you is that your data types should be something like this:
Interface AccountRefPart {
value: string
name: string
}
Interface JournalEntryLineDetailPart {
PostingType: string
AccountRef: AccountRefPart
}
Interface LinePart {
ID?: string
Description: string
Amount: number
DetailType: string
JournalEntryLineDetail: JournalEntryLineDetailPart
}
Interface TableData {
Line: LinePart[]
}
If you just want to pass a single Line element as a JSON (what the outer-most curly braces suggest), you'll want to stringify a single object of the TableData type, and you want to construct this object using the data from the rows of your table. (I can't actually see your table, but I trust that it has the information you need above.)

How to access the right json value that is located through an array?

I'm currently using the fixture file to make sure it will be easier to call the right value.
cy.fixture('latestLead.json').then(function (lead) {
this.lead = lead
})
My son file is the following:
{
"status": 0,
"result": {
"totalSize": 1,
"done": true,
"records": [
{
"attributes": {
"type": "Lead",
"url": "/services/data/v51.0/sobjects/Lead/111111111"
},
"Id": "111111111",
"Name": "Andres Latest Test"
}
]
}
}
The way that I'm trying to get the right value is the following:
cy.get(".gLFyf").type(this.lead.result.records.Id)
I'm able to get totalSize or done from the result object, but I'm not able to get any other value higher than that object. How can I get the Id value from the records Array?
You can access an array item (in your case it's the object) using the index position (in your case it's zero)
cy.get(".gLFyf").type(this.lead.result.records[0].Id)
try this
cy.get(".gLFyf").type(this.lead.result.records[0].Id)

Parsing JSON array created from PHP array

{
"3": {
"id": "3",
"ocena_ocena": "2",
"ocena_profesor": "\u041c\u0430\u0440\u043a\u043e \u041c\u0430\u0440\u043a\u043e\u0432\u0438\u045b",
"ocena_napomena": "",
"ocena_datum": "31.12.2015."
},
"1": {
"id": "1",
"ocena_ocena": "5",
"ocena_profesor": "\u041c\u0430\u0440\u043a\u043e \u041c\u0430\u0440\u043a\u043e\u0432\u0438\u045b",
"ocena_napomena": "",
"ocena_datum": "22.12.2015."
}
}
I am using ajax to get this JSON. I tried parsing it like this:
request.done(function(response) {
alert(response.ocena_ocena);
});
Could someone please help me with this?
I also need to know how can I do a foreach statement with json?
Since your JSON represents a JavaScript object, you should include the attribute name (if we consider JavaScript object to be a map, then, we need to use the key).
Try
response["1"].ocena_ocena
or
response["3"].ocena_ocena
Since you are returning a JSON object from server instead of an array, to iterate over its properties, you could do
for (var i in response) {
console.log(response[i].ocena_ocena);
}
or
Object.keys(response).forEach(function f(e) {console.log(response[e].ocena_ocena)})
If you could modify your server side code to return JSON that looks like this,
[
{
"id": "3",
"ocena_ocena": "2",
...
},
{
"id": "1",
"ocena_ocena": "5",
...
}
]
then you could iterate over it more easily
response.forEach(function f(e) {console.log(e.ocena_ocena)})

How to parse a JSON array string in JavaScript?

I have an JSON array like this
var filter_value_data = [{"Status":[{"name":"Open","id":"1"},{"name":"Pending","id":"2"},{"name":"Resolved","id":"3"},{"name":"Closed","id":"4"},{"name":"Evaluation","id":"5"}]},{"Payment Status":[{"name":"Paid","id":"10"},{"name":"UnPaid","id":"11"},{"name":"Part Paid","id":"12"}]},{"Priority":[{"name":"Low","id":"6"},{"name":"Medium","id":"7"},{"name":"High","id":"8"},{"name":"Urgent","id":"9"}]}]
I have tried filter_value_data["Status"] which is obviously wrong. How do I get the JSON elements for Status using the names like Status,Payment Status?
filter_value_data is an array (having []), so use filter_value_data[0].Status to get the first element-object with property "Status".
It is always good to format your code in order to see the hierarchy of the structures:
var filter_value_data = [
{
"Status": [
{
"name": "Open",
"id": "1"
}, {
"name": "Pending",
"id": "2"
}, ...
]
}, {
"Payment Status": [
{
"name": "Paid",
"id": "10"
}, ...
]
}, {
"Priority": [
{
"name": "Low",
"id": "6"
}, ...
]
}
];
With your current JSON you can't get the elements with the name alone.
You can get Status with filter_value_data[0]['Status'] and Payment status with filter_value_data[1]['Payment Status'].
This is because the keys are in seperate objects in the array.
In order to get them with filter_value_data['Status'] you need to change your JSON to
var filter_value_data = {
"Status":[
{"name":"Open","id":"1"},
{"name":"Pending","id":"2"},
{"name":"Resolved","id":"3"},
{"name":"Closed","id":"4"},
{"name":"Evaluation","id":"5"}
],
"Payment Status":[
{"name":"Paid","id":"10"},
{"name":"UnPaid","id":"11"},
{"name":"Part Paid","id":"12"}
],
"Priority":[
{"name":"Low","id":"6"},
{"name":"Medium","id":"7"},
{"name":"High","id":"8"},
{"name":"Urgent","id":"9"}
]
};
I wrote this on my phone so it's not as well-formatted as usual. I'll change it ASAP.
With your current JSON, created a result which might be helpful for you.
JS:
$.each(filter_value_data,function(ind,val){
var sta = val.Status; // Status Object get displayed
for(var i=0;i<sta.length;i++){
var idVal= sta[i].id;
var nameVal = sta[i].name;
Statusarray.push(idVal,nameVal);
console.log(Statusarray);
}
})
FiddleDemo
You can use below code, it will return status object
filter_value_data[0]['Status']
filter_value_data[0]['Payment Status']
to get Single value you use :
filter_value_data[0]['Status'][0]['name']

How do I access an '#attr' value in JSON with jQuery

I'm working with the last.fm api to get artist images, and I'm getting JSON results where I need to check an '#attr' value. Unfortunately, I can't seem to access this value. The results look something like:
{"image":[{
"url":"http:\/\/www.last.fm\/music\/Undefined\/+images\/3040021",
"format":"jpg",
"sizes":{"size":{"#text":"http:...jpg","name":"original","width":"397","height":"397"},{"#text":"http:...jpg","name":"large","width":"126","height":"126"},]},
"#attr":{"official":"yes"}}
it's that last value that I can't get to...
any ideas?
I tried ['#attr'] and it didnt' seem to work - only returned undefined.
I'm doing an $.each(obj.image, function(){}) - and within i'm successfully getting this.url, this.format, etc - but i'm not having luck with this['#attr']
Use the bracket notation member operator:
var value = obj[0]['#attr'];
Then you can access the official property by:
value.official;
Or
obj[0]['#attr']['official'];
Or
obj[0]['#attr'].official;
Edit: As Jonathan pointed out, you have issues with the JSON structure you post, I would recommend you to validate your JSON with a tool like JSONLint.
But I think that you mean something like this:
var obj = {
"image": [{
"url": "http:\/\/www.last.fm\/music\/Undefined\/+images\/3040021",
"format": "jpg",
"sizes": [{
"#text": "http:...jpg",
"name": "original",
"width": "397",
"height": "397"
},
{
"#text": "http:...jpg",
"name": "large",
"width": "126",
"height": "126"
}
],
"#attr": {
"official": "yes"
}
}]
};
And with that JSON structure you can iterate it by:
$.each(obj.image, function () {
alert(this['#attr'].official);
});
You have quite a few formatting issues in your snippet. If these are the same in your actual JSON, you're going to have parsing and object-structure conflicts from what you're probably expecting.
{ /* no matching end */
"images": [ /* no matching end */
{
"url":"http:\/\/www.last.fm\/music\/Undefined\/+images\/3040021",
"format":"jpg",
"sizes": { /* should this be an array instead? */
"size": {
"#text":"http:...jpg",
"name":"original",
"width":"397",
"height":"397"
},
{ /* missing key */
"#text":"http:...jpg",
"name":"large",
"width":"126",
"height":"126"
}, /* trailing comma can cause parsing issues */
] /* no matching start */
},
"#attr": { "official":"yes" }
}

Categories