get json object attribute with 'dot' in name - json

*** Problem solved : json.stringify was the problem.. much easier to handle when its gone.
var DBName = result['Document']['SW.Blocks.GlobalDB']['AttributeList']['Name'];
I have a xml file which describes a datablock from a PLC and want to get specific values with JS.
I converted it with xml2js module, so i have a json object to work with.
{
"Document": {
"Engineering": {
"$": {
"version": "V15"
}
},
"SW.Blocks.GlobalDB": {
"$": {
"ID": "0"
},
"HeaderAuthor": "",
"HeaderFamily": "",
"HeaderName": "",
"HeaderVersion": "0.1",
"Interface": {
...
...
"Name": "datentypen",
"Number": "6",
"ParameterModified": {
"_": "2018-09-05T11:49:37.0862092Z",
"$": {
"ReadOnly": "true"
}
},
}
}
I want to print out the "Name" and the "Number", which are part of the "AttributeList".
So how to handle with the "SW.Blocks.GlobalDB"?
Getting error : "TypeError: Cannot read property 'SW' of undefined"
var fs = require('fs');
var xml2js = require('xml2js');
var xml = fs.readFileSync('datentypen.xml');
var parser = new xml2js.Parser({explicitArray: false});
parser.parseString(xml, function(err, result) {
if (err) {
console.error('xml2js.parse error: ',err);
} else {
var injson = JSON.stringify(result,null,3);
console.log(injson);
// var injson2 = JSON.parse(injson);
// var DBnummer = injson.Document.SW.Blocks.GlobalDB.AttributeList["Name","Number"];
// console.log(DBNummer);
};
});
I read a lot about this theme but didnt found a concrete answer..
When i write ["SW.Blocks.GlobalDB"], an error about [ comes around.

Can you try reading the JSON array using Key-Value pair? I had similar issues but with a different programming language.

Related

How to use variable inside JSON file as prefix

I have the a JSON file and a need to add a prefix variable in some fields, but did not work pass the variable using $variable, {variable}, etc.
My Original JSON file is shown below.
{
"SETUP": {
"mission": "P:\Project",
"mission_type": "0",
"fortnight": "25",
"tide": "0"
},
"MISSION": {
"INPUT": {
"arms": "\cp\arms.ini",
},
}
I need to add the SETUP.mission prefix to the field Mission.INPUT.arms
{
"SETUP": {
"mission": "P:\Project",
"mission_type": "0",
"fortnight": "25",
"tide": "0"
},
"MISSION": {
"INPUT": {
"arms": SETUP.mission + "\cp\arms.ini",
},
}
MISSION.INPUT.arms = "P:\Project\cp\arms.ini"
Thank you
JSON doesn't have a concept of variables. What you need to do is to load it on memory, modify it and save back to the file if needed.
Here's an example of doing it in Node.js:
const fs = require('fs');
const path = require('path');
const json = require('./path/to/json/file.json');
json.MISSION.INPUT.arms = path.join(json.SETUP.mission, json.MISSION.INPUT.arms);
fs.writeFileSync('./path/to/json/file.json', JSON.stringify(json));

getting the error like JSON schema is not correct. Enter specified JSON scehma.,Create an Array of Favorite fruits Object

0
I have the following assessment which is to Create Array of Favorite Food items object in data.json file.
The Array of Objects should have the following fields :
Name
Type
Price
After writing the JSON data, this file should be imported in loopobject.js.
I tried the above request with the below data.json
data.json
"{[{\"Name\":\"Apple\",\"Type\":\"fruit\",\"Price\":123},{\"Name\":\"pizza\",\"Type\":\"italian\",\"Price\":360},{\"Name\":\"burger\",\"Type\":\"mac&cheese\",\"Price\":321},{\"Name\":\"jangri\",\"Type\":\"sweet\",\"Price\":329}]}"
loopObject.js
var json = require('./data.json');
json.forEach(function(object) { console.log(object.Name); });
verify.js
const Joi = require('joi');
const fss =require('fs');
const schema = Joi.array().min(3).has({
Name: Joi.string().required(),
Type: Joi.string().required(),
Price: Joi.number().required(),
});
var data;
try{
data = require("./data.json");
}catch(e)
{
data={};
}
var XMLWriter = require('xml-writer');
xw = new XMLWriter;
const result = Joi.validate(data, schema);
// You can also pass a callback which will be called synchronously with the validation result.
Joi.validate(data, schema, function (err, value) {
if(err==null)
{ console.log("JSON is valid.");
}else{
console.log("JSON schema is not correct. Enter specified JSON scehma.");
}
});
i have tried couple of ways, everything looks good,but don't know where i am doing mistake. Could you please help on this??
The JSON format is not correct, try this one:
data.json
[
{
"Name": "someName",
"Type": "someType",
"Price": 123
},
{
"Name": "someName",
"Type": "someType",
"Price": 123
},
{
"Name": "someName",
"Type": "someType",
"Price": 123
},
{
"Name": "someName",
"Type": "someType",
"Price": 123
}
]
The JSON data describes an array, and each element of that array is an object.

GULP Create JSON file from another JSON file

I am trying to create a local lang file that will be formatted as json. I have the following navigation in json format below. And I need to create a new JSON file using GULP to create a lang file (see below)
"lists": [
{
"title": "Application Intel",
"items": [
{
"title": "Analytics Dashboard",
"href": "intel_analytics_dashboard.html"
},
{
"title": "Marketing Dashboard",
"href": "intel_marketing_dashboard.html"
},
{
"title": "CEO Dashboard",
"href": "intel_ceo_dashboard.html"
},
{
"title": "Introduction",
"href": "intel_introduction.html"
},
{
"title": "Build Notes",
"href": "intel_build_notes.html",
"text": "Build Notes",
"span": {
"class": "",
"text": "v{{version}}"
}
}
]
}
I need to create a file that looks like the following json:
"nav": {
"application_intel": "Application Intel",
"intel_analytics_dashboard": "Analytics Dashboard",
"intel_marketing_dashboard": "Marketing Dashboard",
"intel_ceo_dashboard": "CEO Dashboard",
"intel_introduction": "Introduction",
"intel_build_notes": "Build Notes",
}
Whats the best way to go about this?
Here is solution.
Let's say you have nav.json file inside src and you want to change its shape and place it into dest directory. You can achieve this from within gulpfile.js
const { src, dest } = require("gulp");
const through = require("through2");
// gulp task
function json() {
return src("src/nav.json")
.pipe(
through.obj((file, enc, cb) => {
// get content of json file
const rawJSON = file.contents.toString();
// parse raw json into javscript object
const parsed = JSON.parse(rawJSON);
// transform json into desired shape
const transformed = transformJson(parsed);
// make string from javascript obj
const stringified = JSON.stringify(transformed, null, 2);
// make bufer from string and attach it as current file content
file.contents = Buffer.from(stringified);
// pass transformed file into next gulp pipe
cb(null, file);
})
)
.pipe(dest("dest"));
}
// transformation
function transformJson(input) {
const result = { nav: {} };
// read json field by field
Object.keys(input).forEach(topLevelKey => {
// current object
const topLevelItem = input[topLevelKey];
// in your design topLevelItems are arrays
topLevelItem.forEach(menuItem => {
if (menuItem.title) {
// make url either from item href or title
const itemUrl = makeUrl(menuItem.href || menuItem.title);
result.nav[itemUrl] = menuItem.title;
}
// prcoess children
if (menuItem.items) {
menuItem.items
.filter(child => !!child.title) // process only child items with title
.forEach(child => {
const childUrl = makeUrl(child.href || child.title);
result.nav[childUrl] = child.title;
});
}
});
});
return result;
}
// helper func
function makeUrl(href) {
return href
.toLowerCase()
.replace(/\.html$/, "")
.replace(/\s/g, "_");
}
// export for use in command line
exports.json = json;
json transformation function is bit forEachy and if you have deep nested navigation structure, maybe you should change it into something recursive

JSON Import with Javascript, how to skip deferred exception?

I have written an javascript importer for a external json dataset
<script type="text/javascript" src="data.json"></script>
var importData = JSON.stringify(data);
var importCompany = data.report.company.name;
if(importCompany != ''){
jQuery('.company .name').text(importCompany);
}
All working perfectly :D
My issue is when I update the script to read data2.json and data.report.company.name doesn't exist, I get this error in the developer console
jQuery.Deferred exception: Cannot read property 'name' of undefined TypeError: Cannot read property 'name' of undefined
How do i overcome this issue?
Thanks
EDIT
data.json (external)
var data = {
"report": {
"company": {
"name": "XXX"
"other": "123"
},
"information": "GB-0-01777777",
"references": "2018-06-26T07:48:41.104Z"
}
data2.json (external)
var data = {
"report": {
"company": {
"other": "123"
},
"information": "GB-0-01777777",
"references": "2018-06-26T07:48:41.104Z"
}

get json value object from mongodb

I have formData node that has dynamic jsonObject value in mongodb
{
"_id": {
"$oid": "5a71fea0f36d2848ae4f8f0a"
},
"formData": {
"pages": [
{
"name": "page1",
"questions": [
{
"type": "comment",
"name": "about",
"title": "Please tell us about your main requirements "
}
]
}
]
},
"editorId": "59678e58f36d2842f777bc48",
"datetimeSubmit": "2018/01/15"
}
I write a node API to fetch the data from mongodb, it only display ids, editorI and datetimesubmit nodes, but it ignores the formData(jsondata) field.
const Model = require('./myModel');
module.exports = {
getData: function (callback) {
Model.find({}, (err, jsonObj) => {
callback(null, {
data: jsonObj
})
})
}
}
looks like the model.find() doesn't return jsonObject value?
thanks
got my own question fixed, basically, i should also define the data type as JSON in schema, otherwise, will be ignored.