Get specific field from property - javascript

I am new to JavaScript and Dynamics CRM.
I have following code:
var analysisCode = Xrm.Page.getAttribute("rf_analysiscode").getValue()[0].entityValues;
As value for analysisCode, I get following output:
{
"rf_name":{"name":"rf_name","value":"ABC"},
"rf_code":{"name":"rf_code","value":"ABC"},
"createdon":{"name":"createdon","value":"24.1.2022 10.39"}
}
But I want to get just the rf_code. How do I retrieve that?

Parse your result to JSON like this:
const analysisCodeObj = JSON.parse(analysisCode);
Get rf_code like this:
const rfCodeObj = analysisCodeObj["rf_code"];

Try this:
analysisCode = {
"rf_name":{"name":"rf_name","value":"ABC"},
"rf_code":{"name":"rf_code","value":"ABC"},
"createdon":{"name":"createdon","value":"24.1.2022 10.39"}
};
let rf_code = analysisCode.rf_code;
console.log('rf_code : ', rf_code);
console.log('rf_code Value : ', rf_code.value);
If you are getting your output in String, Firstly need to parse output and then you can get any value from that json.
Try this:
analysisCode = '{"rf_name":{"name":"rf_name","value":"ABC"},"rf_code":{"name":"rf_code","value":"ABC"},"createdon":{"name":"createdon","value":"24.1.2022 10.39"}}'
let rf_code = JSON.parse(analysisCode).rf_code;
console.log('rf_code : ', rf_code);
console.log('rf_code Value : ', rf_code.value);

Related

How can I convert this text to JSON by nodejs?

How can I convert this text to JSON by nodejs?
Input :
---
title:Hello World
tags:java,C#,python
---
## Hello World
```C#
Console.WriteLine(""Hello World"");
```
Expected output :
{
title:"Hello World",
tags:["java","C#","python"],
content:"## Hello World\n```C#\nConsole.WriteLine(\"Hello World\"");\n```"
}
What I've tried to think :
use regex to get key:value array, like below:
---
{key}:{value}
---
then check if key equals tags then use string.split function by , to get tags values array else return value.
other part is content value.
but I have no idea how to implement it by nodejs.
If the input is in a known format then you should use a battle tested library to convert the input into json especially if the input is extremeley dynamic in nature, otherwise depending on how much dynamic is the input you might be able to build a parser easily.
Assuming the input is of a static structure as you posted then the following should do the work
function convertToJson(str) {
const arr = str.split('---').filter(str => str !== '')
const tagsAndTitle = arr[0]
const tagsAndTitleArr = tagsAndTitle.split('\n').filter(str => str !== '')
const titleWithTitleLabel = tagsAndTitleArr[0]
const tagsWithTagsLabel = tagsAndTitleArr[1]
const tagsWithoutTagsLabel = tagsWithTagsLabel.slice(tagsWithTagsLabel.indexOf(':') + 1)
const titleWithoutTitleLabel = titleWithTitleLabel.slice(titleWithTitleLabel.indexOf(':') + 1)
const tags = tagsWithoutTagsLabel.split(',')
const result = {
title: titleWithoutTitleLabel,
tags,
content: arr[1].slice(0, arr[1].length - 1).slice(1) // get rid of the first new line, and last new line
}
return JSON.stringify(result)
}
const x = `---
title:Hello World
tags:java,C#,python
---
## Hello World
\`\`\`C#
Console.WriteLine(""Hello World"");
\`\`\`
`
console.log(convertToJson(x))
Looks like you're trying to convert markdown to JSON. Take a look at markdown-to-json.
You can also use a markdown parser (like markdown-it) to get tokens out of the text which you'd have to parse further.
In this specific case, if your data is precisely structured like that, you can try this:
const fs = require("fs");
fs.readFile("input.txt", "utf8", function (err, data) {
if (err) {
return console.log(err);
}
const obj = {
title: "",
tags: [],
content: "",
};
const content = [];
data.split("\n").map((line) => {
if (!line.startsWith("---")) {
if (line.startsWith("title:")) {
obj.title = line.substring(6);
} else if (line.startsWith("tags")) {
obj.tags = line.substring(4).split(",");
} else {
content.push(line);
}
}
});
obj.content = content.join("\n");
fs.writeFileSync("output.json", JSON.stringify(obj));
});
Then you just wrap the whole fs.readFile in a loop to process multiple inputs.
Note that you need each input to be in a separate file and structured EXACTLY the way you mentioned in your question for this to work. For more general usage, probably try some existing npm packages like others suggest so you do not reinvent the wheel.

Json key and value in javascript

My Link json test file is the following:
[{"google" : "https://google.com"},{"bing" : "https://bing.com"}]
The javascript requesting the value, using axios:
var Links = './Links'
axios.get(Links)
.then(function(response){
console.log(response.data["google"]);
try {
var Test12 = JSON.stringify(response.data["google"]);
} catch (err) {
var Test12 = 'nothing'
}
The result is undefined.
My goal is to return the value of the input "google" or any input from the JSON and store it in the var as a string.
Since its an array of objects so you should access the values like,
response.data[0].google
OR
response.data[0]["google"]
Your data file is a list with two objects in it.
To access the google item you should access the list element.
var Test12 = JSON.stringify(response.data[0]["google"]);
Although I would change the json file to:
{"google" : "https://google.com", "bing" : "https://bing.com"}
Maybe like this:
var data=[{"google" : "https://google.com"},{"bing" : "https://bing.com"}];
data.forEach(function(el, index) {
Object.keys(el).forEach(function(val) {
console.log(val + " => " + el[val]);
});
});

JSON.parse returning [Object Object] instead of value

My API returning the JSON value like
[{"UserName":"xxx","Rolename":"yyy"}]
I need Username and RoleName value seperatly i tried JSON.parse but its returning [Object Object] Please help me thanks in advance
Consider the following:
var str = '[{"UserName":"xxx","Rolename":"yyy"}]'; // your response in a string
var parsed = JSON.parse(str); // an *array* that contains the user
var user = parsed[0]; // a simple user
console.log(user.UserName); // you'll get xxx
console.log(user.Rolename); // you'll get yyy
If your data is a string then you need to parse it with JSON.parse() otherwise you don't need to, you simply access it as is.
// if data is not in string format
const data = [{"UserName":"xxx","Rolename":"yyy"}];
const username = data[0].UserName
const rolename = data[0].Rolename
console.log(username)
console.log(rolename)
// if data is in string format
const strData = JSON.parse('[{"UserName":"xxx","Rolename":"yyy"}]');
const Username = strData[0].UserName
const Rolename = strData[0].Rolename
console.log(Username)
console.log(Rolename)
You have an array. Then need to get 0th element very first
This will work
let unps = JSON.parse('[{"UserName":"xxx","Rolename":"yyy"}]')[0]
console.log(unps.UserName, unps.Rolename);

Handle Json data and pass it to object for further use

For instance I have some JSON data like below (The JSON data is just an example, I just want to give out some fake, make up and wrong format JSON as example)
cata :[{
name:test1,
data:['abc1, abc2' , 'abc3,abc4']
}
name:test2,
data:['abc5, abc6' , 'abc7,abc8']
}]
And indeed I need to render it to frontend, therefore I made a new object and try to push data into it
var name = "";
var key= [];
for(var i=0;i<2;i++){
name .push(cata[i].name)
key.push(cata[i].data.join(' + '));
}
var rehandle = {
name : name,
key : key
}
The above is just how i do it now, and which do no provide the desire result, i want to know how could i restore it so i can change the format from
['abc5, abc6' , 'abc7,abc8']
to
abc5+abc6 , abc7+abc8
UPDATE version of the question:
I think i better explain it step by step:
I have some raw data
I have a row of "data" in each set of data
(E.g:data:['abc1, abc2' , 'abc3,abc4'])
I want to change it's format to abc1+abc2 , abc3+abc4 and store it to another variable
I will pass the variable store abc1+abc2 , abc3+abc4 to an object
5.Render it one by one in a table
UPDATE 2
I have seen #pill's answer, am i able to render the data like
for(var i=0;i<cata.length;i++){
var trythis = trythis + '<td>'+name[i]+'</td>' + '<td>'+data[i]+'</td>'
}
To format your data from
['abc5, abc6' , 'abc7,abc8']
to
abc5+abc6 , abc7+abc8
you'd simply use
data.map(k => k.split(/,\s*/).join('+')).join(' , ')
or the ES5 version
data.map(function(k) {
return k.split(/,\s*/).join('+');
}).join(' , ');
For example...
var cata = [{"name":"test1","data":["abc1, abc2","abc3,abc4"]},{"name":"test2","data":["abc5, abc6","abc7,abc8"]}];
var rehandle = cata.reduce(function(o, d) {
o.name.push(d.name);
o.key.push(d.data.map(function(k) {
return k.split(/,\s*/).join('+');
}).join(' , '));
return o;
}, {
name: [],
key: []
});
console.log('rehandle:', rehandle);
Note that I had to fix up your data formatting

How to access value of variable in Mongo?

var a = "act";
db.s.findOne( {
BrandId: doc.BrandId,
a : {$exists:false}
} ).a;
I try to pass the value of variable "a" to my MongoScript. But it looks it can not be simply used. anyone can help?
Build your query step by step and do not use . use [] instead
var a = 'act';
var query = {BrandId: doc.BrandId};
query[a] = {$exists:false};
db.s.findOne(query)[a];
Note:
query.act == query['act'].
Just some javascript tricks.

Categories