I use axios to make it. How to receive data in XML when I make an request API?
Example:
axios.get(/* URL */).then(response => {/* How to get data XML? */}).catch(err => {/* result */});
In your .then callback, the response has a property data it is the xml document as a string. Many people would use this string and parse it using a parser that is build into the browser, like it is demonstrated in this very recent question:
Reading local text file as XML
I however would recomment using a parser library, these provide a much more effective way of working with xml data. My choice is txml.
you can get it into your document like this:
<script src="https://unpkg.com/txml#4.0.0/tXml.min.js"></script>
Then, when you parse the xml string like this:
axios.get(/* URL */).then(response => {
const dom = txml.parse(response.data);
}).catch(err => {/* result */});
The constant dom, is an array, of xml nodes. each node has the properties tagName, attributes and children. children is again an array of nodes.
the library has very handy helper functions like 'txml.simplify(dom)' will give you an object, that looks more like a data object. you can check the API documentation on npm.
DISCLAIMER: I am the author of txml.
Related
I have a lot of data loaded in my database where some of the documents loaded are not JSON files & just binary files. Correct data looks like this: "/foo/bar/1.json" but the incorrect data is in the format of "/foo/bar/*". Is there a mechanism in MarkLogic using JavaScript where I can filter out this junk data and delete them?
PS: I'm unable to extract files with mlcp that have a "?" in the URI and maybe when I try to reload this data I get this error. Any way to fix that extract along with this?
If all of the document URIs contain a ? and are in that directory, then you could use cts.uriMatch()
declareUpdate();
for (const uri of cts.uriMatch('/foo/bar/*?*') ) {
xdmp.documentDelete(uri)
}
Alternatively, if you are looking to find the binary() documents, you can apply the format-binary option to a cts.search() with a cts.directoryQuery() and then delete them.
declareUpdate();
for (const doc of cts.search(cts.directoryQuery("/foo/bar/"), ['format-json']) ) {
xdmp.documentDelete(fn.baseUri(doc));
}
They are probably being persisted as binary because there is no file extension when the URI ends with a question mark and some querystring parameter values i.e. 1.json?foo=bar instead of 1.json
It is difficult to diagnose and troubleshoot without seeing what your MLCP job configs are and knowing more about what you are doing to load the data.
I have a JSON object in my database that contains html inside it. I pass the object as part of a model to my view. I need to access the object and read it in the javascript files for the page. However when i try and assign the object to a global variable in my html file i cannot access it in my javascript file.
I tried reading the object as a string it returns decoded html (
"page-1":) which i cant do anything with. If i call #Html.Raw(#Model.CourseContent.ExpectedResult) it created the JSON object as expected. However in my javascript file it is listed as undefined. I have no idea how to solve this.
#model DataTransferObjects.Models.UserCourseAndContent
<script>
var totalPages = '#Model.CourseContent.TotalPages';
var expectedResults = #HTML.Raw(#Model.CourseContent.ExpectedResult)
</script>
The json object that comes out when i use the above code looks like
var expectedResults = {
"page-1": "<head></head><body></body>",
"page-3": "<head></head><body><h1>My Cool News Article</h1><p>Welcome
to my news article, you’ll find some cool news here.</p>
<Our most recent
news</<p>Below you’ll find my most recent news!</p></body>"
};
I expected it to be an actual json string but instead ive got an object (?) i am confused as to how to decode the html out of it then turn the resulting json obejct into a json string to be read in the javascript file.
Any help would be great!
var expectedResults = {
"page-1": "<head></head><body></body>",
"page-3": "<head></head><body><h1>My Cool News Article</h1><p>Welcome
to my news article, you’ll find some cool news here.</p>
<Our most recent
news</<p>Below you’ll find my most recent news!</p></body>"
};
// Parse JSON
const parsedJSON = JSON.parse(JSON.stringify(expectedResults));
// Access to properties
const page-1 = parsedJSON['page-1'];
const page-3 = parsedJSON['page-3'];
I am optimizing an api, therefore I need to use only data that is relevant for my analysis. I have created a route that pull out of the objects, but I just need 4 of them (account_manager, fronter, closer, management_fee and sales_date)
I am currently doing this:
you can use .find() with projection to retrieve only the relevant field
try this :
const model_CancellationKPI = await CancellationKPI.find({},{
account_manager:1,
fronter:1,
closer:1,
management_fee:1,
sales_date:1
}).sort({sales_date:-1})
I'm hoping to use a Google Sheets CSV as a data source. I'd like to fetch the CSV data on the client, then convert into JSON.
I'm able to fetch the CSV, which returns a ReadableStream. However, I'm not sure how to correctly read that response and convert into JSON.
I've found an npm package which should help convert the CSV data to JSON, but having a little bit of a time working with the stream.
Example: https://jsfiddle.net/21jeq1h5/3/
Can anyone point me in the right direction to use the ReadableStream?
Since CSV is simply text, the solution is the use the response.text() method of the fetch() API.
https://developer.mozilla.org/en-US/docs/Web/API/Body/text
Once the text is onboard, it is as simple as parsing the CSV out of the file. If you want objects as an output it is imperative the headers are included in the CSV (which yours are).
I've included the code snippet below. It won't run on SO because SO sets the origin to null on AJAX requests. So I've also included a link to a working codepen solution.
fetch('https://docs.google.com/spreadsheets/d/e/KEY&single=true&output=csv')
.then(response => response.text())
.then(transform);
function transform(str) {
let data = str.split('\n').map(i=>i.split(','));
let headers = data.shift();
let output = data.map(d=>{obj = {};headers.map((h,i)=>obj[headers[i]] = d[i]);return obj;});
console.log(output);
}
Pen
https://codepen.io/randycasburn/pen/xjzzvW?editors=0012
Edit
I should add that if you truly want this in a JSON string (per your question), you can run
json = JSON.stringify(output);
This code is written in python:
from asn1crypto import tsp, cms, util
response_file = open('timestamp-response.tsr','rb')
response = tsp.TimeStampResp.load(response_file.read())
token = response['time_stamp_token']
signed_data = token['content']
encap_content_info = signed_data['encap_content_info']
tst_info = encap_content_info['content'].parsed
signer_infos = signed_data['signer_infos']
signer_info = signer_infos[0]
signed_attrs = signer_info['signed_attrs']
signature = signer_info['signature']
I can't find way to perform the same action using javascript even the api of the libraries looks the same.
Helpful links:
https://kjur.github.io/jsrsasign/api/symbols/KJUR.asn1.tsp.TimeStampResp.html
https://github.com/wbond/asn1crypto/blob/master/asn1crypto/tsp.py
I am not aware of any ready-to-use library but I believe it should be possible to use ASN1.js to parse TimeStampResp structure with definitions from RFC3161 and extract the data you need.
Parsing DER encoded structure when you have its ASN.1 definition is the same thing as parsing XML structure when you have its XSD definition but it will probably take more time until you get familiar with ASN.1 stuff.
You could try pkijs. I did not try it on timestamps (only x509 certificates) but it seems this library does support it. It uses asn1js under the cover.
Time-stamping request:
Parsing internal values
Getting/setting any internal values
Creation of a new Time-stamping request "from scratch"
Validation of Time-stamping request signature
Time-stamping response:
Parsing internal values
Getting/setting any internal values
Creation of a new Time-stamping response "from scratch"
Validation of Time-stamping response signature