Convert yaml to json using javascript [duplicate] - javascript

This question already has answers here:
JavaScript YAML Parser [closed]
(4 answers)
Closed 6 years ago.
I got this yaml file:
description:
is_a: AnnotationProperty
labelEN: description
labelPT: descrição
relevance:
is_a: AnnotationProperty
domain: Indicator
labelEN: relevance
labelPT: relevância
title:
is_a: AnnotationProperty
labelPT: título
labelEN: title
range: Literal
and I need to convert it to json, so I can get something like this:
{
"description": {
"is_a": "AnnotationProperty",
"labelEN": "description",
"labelPT": "descrição"
},
"relevance": {
"is_a": "AnnotationProperty",
"domain": "Indicator",
"labelEN": "relevance",
"labelPT": "relevância"
},
"title": {
"is_a": "AnnotationProperty",
"labelPT": "título",
"labelEN": "title",
"range": "Literal"
}
}
and save it in a js variable...
So, how can I do this?
Hey, please check link below for YAML to JSON converter
https://www.yamlonline.com/

You can solve that with a simple javascript script running on node.
install node.js
install the js-yaml package: npm install js-yaml -g
Then save this script into a file, and run it with node.js:
var inputfile = 'input.yml',
outputfile = 'output.json',
yaml = require('js-yaml'),
fs = require('fs'),
obj = yaml.load(fs.readFileSync(inputfile, {encoding: 'utf-8'}));
// this code if you want to save
fs.writeFileSync(outputfile, JSON.stringify(obj, null, 2));

There is—unfortunately—nothing in the standard library in JavaScript that will do this for you.
It's possible to build your own, but it's a lot of work. You would have to build a parser and there are likely a lot of edge cases that you would have to solve for. It might be worth considering using a third-party module.

Related

How to convert json to xml usin npm packages whic is jsontoxml

I want to convert json to xml. I already have used https://www.npmjs.com/package/xml-js npm package. Its output like :
<0>
<name>Autofac</name>
<version>
<Version>4.9.0.0</Version>
<SpecialVersion/>
</version>
<ProjectName>PIWorks.Son.UI.Migrations</ProjectName>
<licenseFile>C:\PIWorks\PISon.UI\licenses\NuGet\Autofac#4.9.0LICENSE.txt</licenseFile>
<repository>https://opensource.org/licenses/mit-license.php</repository>
</0>
But I want to use https://www.npmjs.com/package/jsontoxml
When I used this packages output like this:
<System.Threading.Timer/><System.ValueTuple/><System.Xml.ReaderWriter/><System.Xml.XDocument/><WebGrease/><YUICompressor.NET/>
I cannot understand anything what I am wrong.
Its also my json:
{
"name": "Autofac",
"version": {
"Version": "4.9.0.0",
"SpecialVersion": ""
},
"repository": "https://opensource.org/licenses/mit-license.php"
}
I need a help.

Retrieve or Specify output file name in electron-builder

I am working with electron-builder programmatically to generate installation packages. So far I have this as my utility to create the installation package for the current OS type:
const packagejson = require("../package.json");
const builder = require("electron-builder");
const Platform = builder.Platform;
function buildPromise(){
//Development package.json
const devMetadata = packagejson.electronBuilder;
//Application package.json
const appMetadata = {
name: packagejson.name,
version: packagejson.version,
description: packagejson.description,
author: packagejson.author,
productName: packagejson.productName
};
//Build for the current target and send back promise
return builder.build({
projectDir: "./",
devMetadata,
appMetadata
});
}
module.exports = {
buildPromise,
outputPath : packagejson.electronBuilder.directories.output
};
What it does is pull in the needed metadata from the apps MAIN package.json file which contains this section (so the application package.json is empty):
...
"electronBuilder": {
"build": {
"productName": "Node App",
"appId": "my.id",
"asar": false,
"win": {
"iconUrl": "http://localhost:5000/images/logo-multi.ico",
"target": "nsis"
},
"nsis" :{
"oneClick": false
}
},
"directories": {
"output": "electron/output",
"app":"electron/app",
"buildResources": "electron/buildResources"
}
}
...
When I run the build in Windows I get a file out called Node App Setup 1.0.0.exe. So far so go. But how do I actually control that final file name? Or at least retrieve that file name programmatically so I can read it in and respond to the client in some way? Obviously, I could piece it together from the json file settings but it I would rather it be more definitive.
You can specify the output filename using artifactName in the build section of your package.json.
The docs say the artifact file name template supports the ${ext} macro:
${ext} macro is supported in addition to file macros.
File Macros
You can use macros in the file patterns, artifact file name patterns and publish configuration url:
${arch} — expanded to ia32, x64. If no arch, macro will be removed from your pattern with leading space, - and _ (so, you don't need to worry and can reuse pattern).
${os} — expanded to mac, linux or win according to target platform.
${name} – package.json name.
${productName} — Sanitized product name.
${version} — from package.json
${channel} — detected prerelease component from version (e.g. beta).
${env.ENV_NAME} — any environment variable.
Any property of AppInfo (e.g. buildVersion, buildNumber).
Example
"build": {
"appId": "com.electron.app.my",
"artifactName": "node-app-${version}.${ext}",
...
},
If your package version is 1.0.0, a Windows target would output:
node-app-1.0.0.exe
At my request the author added it to the current version (8.5.1):
https://github.com/electron-userland/electron-builder/issues/899
so now we can do:
builder.build()
.then(paths => {
//paths contains an array of export file paths, e.g.:
console.log(paths[0]); //= c:/MyProject/dist/My Project Setup 1.0.0.exe
console.log(paths[1]); //= c:/MyProject/dist/myproject-1.0.0-x86_64.AppImage
});

how to read the data from a text file to inssert to mongodb in java script

I have a sample data file which contains few hundred records as shown below
{
"roadInfo": {
"roadId": "1",
"roadName": "Airport Boulevard",
"laneCount": 5
},
data:123
},
{
"roadInfo": {
"roadId": "1",
"roadName": "Airport Boulevard",
"laneCount": 5
},
data:123
}
.
.
.
.
.
.
n
I am looking for a way to read this json payload and insert in a mongodb collection (now i am manually inserting it)
Can some one please point out way to do it
You should be able to use mongoimport for that. While connected to the mongod instance that your db exists on with the mongo shell, run a command like mongoimport --db dbName --collection collectionName --file file.json.
While this is specifically made to import JSON files created from mongoexport, mongoimport should work as long as it doesn't violate the use of strict data types explained here.
The other options is writing an import using Node.js fs.readFile() methods and the mongodb driver or a wrapper/ORM of your choice (mongoose, monk, mongoskin, etc.). And here's a decent article on how to read the JSON file in Node.

Kartograph: Map Creation fails

Recently I started using Kartograph. I am inexperienced in SVG, so the map creation is creating headaches for me. After initial trouble creating a world map that outlines country borders - similar to this - and a few other things(city regions and some decorating elements), my problem boils down to a undocumented - or at least I haven't found it in the docs - error. I guess it is related with my ignorance towards the kartograph.py framework.
The json file I provide Kartograph looks like that:
{
"proj": {
"id": "lonlat",
"lon0": 20,
"lat0": 0
},
"layers": {
"background": {
"special": "sea",
"charset": "latin-1",
"simplify": false
},
"graticule": {
"special": "graticule",
"charset": "latin-1",
"simplify": false,
"latitudes": 1,
"longitudes": 1,
"styles":{
"stroke-width": "0.3px"
}
},
"world":{
"src": "ne_50m_admin_0_countries.shp",
"charset": "latin-1",
"simplify": false
},
"lakes":{
"src": "Lakes.shp",
"charset": "latin-1",
"simplify": false
},
"trees":{
"src": "Trees.shp",
"charset": "latin-1",
"simplify": false
},
"depth":{
"src": "DepthContours.shp",
"charset": "latin-1",
"simplify": false
},
"cities":{
"src": "CityAreas.shp",
"charset": "latin-1",
"simplify": false
}
}
}
I know the output file will be huge and the generation will take ages, but it is just a test. I will experiment with the "simplify" option later. Much of the code in the file is based on this tutorial. Also, the empty simplify clause might not be necessary, but kartograph complained about the lack of the option, so I added it.
The command I use is this one:
kartograph world.json -o world.svg
It runs for some time(I guess, parsing all the input files etc.) before aborting. Now, the error I am facing is this one:
cli.py, in render_map()
71: K.generate(cfg, args.output, preview=args.preview, format=format, stylesheet=css) kartograph.py, in generate()
46: _map = Map(opts, self.layerCache, format=format) map.py, in __init__()
50: me.bounds_poly = me._init_bounds() map.py, in _init_bounds()
192: features = self._get_bounding_geometry() map.py, in _get_bounding_geometry()
257: charset=layer.options['charset']
get_features() got an unexpected keyword argument 'filter'
I tried looking at the file which throws the error(map.py), but I realized quickly that there's just too much interaction in the files for me to grasp things quickly.
I hope the data I provided is sufficient for someone more familiar with kartograph than me to track the error down.
UPDATE: The error is still valid. I tested it on both a MacBook Pro and an Asus Netbook now(Arch and Bodhi Linux, respectively).
Thanks in advance,
Carson
As far as I know, you can solve that problem by including a 'bounds' parameter. It is in deed very tricky, because according to the documentation (is it valid to call it 'documentation') this error should not appear, since the only required parameter is 'layers'. Also, how the bounds are defined depend apparently from the chosen projection. For your example I would use a simple polygon bounds.
I also had problems with that error. But, after many trials to set up everything, I noticed that apparently it only appears in the command-line version of Kartograph, and not when using Kartograph as a Python module in a script. I.e., try to include the json dictionary into a Python script where you import kartograph, like in the example here below.
I also put an example of filtering, for the record, because it was another thing that failed to work when using the command-line version of Kartograph.
# file: makeMap.py
from kartograph import Kartograph
K = Kartograph()
def myfilter(record):
return record['iso_a3'] in ["FRA","ITA","DEU"]
config = {
"layers": {
"mylayer": {
"src": "ne_50m_admin_0_countries.shp",
"filter": myfilter,
"attributes": {"iso_a3":"iso_a3", "name":"name", "id":"iso_a3"}
}
},
}
K.generate(config, outfile='world.svg')
Then, run the script as a Python script:
python makeMap.py

Implement js plugin for sublime text 2 using v8 plugin

I am trying to write plugins for sublime text 2 in javascript, using the v8 plugin. There is a demo javascript file called test.js, which seems to be a complete test plugin, but I can not figure out how to activate it.
Has anyone managed to write a plugin for sublime text 2 using javascript?
Is there another way to approach this? I mostly want to send text to javascript to be processed by my various libraries and then send text back.
EDIT:
I am using this project to get v8 working with sublime: https://github.com/akira-cn/sublime-v8
You can try this plugin https://github.com/akira-cn/SublimeJS
Follow example:
/** package.json **/
{
"name": "JSDemo",
"description": "demo plugin powered by SublimeJS",
"version": "0.1.0",
"author": {
"name": "akira-cn",
"email": "akira.cn#gmail.com"
},
"main": "index.js",
"licenses": [{
"type": "The MIT License",
"url": "http://www.opensource.org/licenses/mit-license.php"
}]
}
/** index.js **/
defineCommand("Hello", require("hello.command"));
/** hello.command.js **/
module.exports = function(view, edit) {
view.insert(edit, 0, "HelloWorld");
}
You can do that with node.js. Simple python wrapper should do the trick.
An example of plugin build with node.js: Sublime-HTMLPrettify

Categories