javascript convert JSON string to JSON object - javascript

I al using javascript and looping through the values of a submitted form and trying to build a son object out of the form values.
This is an example of the final object I need:
{
"DataObject": {
"user": { "-name": "username" },
"contentFile": {
"-filename": "Breaking_News",
"lock": { "-fileIsBeingEdited": "false" },
"content": {
"line": [
{
"-index": "1",
"-text": "this is the header"
},
{
"-index": "2",
"-text": "this is the first line"
},
{
"-index": "3",
"-text": "this is the second line"
}
]
}
}
}
}
So far i am adding all of this data to a string as that seems to be the only way i can insert the form values (the line array) into the middle of the object.
var jsonStr = '{'
+ 'iceteaDataObject: {'
+ 'user: {"-name": "hindsc52"},'
+ 'contentFile: {'
+ '"-filename": "Ticker",'
+ 'lock: { "-fileIsBeingEdited": "false" },'
+ 'content: {'
+ 'line: ['
for(var i = 0; i < elem.length; i++) {
if(!elem[i].value == '') {
jsonStr += '{'
jsonStr += "-index: " + i + ',';
jsonStr += "-text: " + elem[i].value;
jsonStr += '},'
}
}
jsonStr += ']}}}}';
console.log(JSON.parse(jsonData));
however when running this I get the error: unexpected token 'i'.
I have tried to use stringily but then just outputs the entire sting again.

You don't need or want JSON for this, just build the object:
// Sample data
var elem = [{
value: "one"
}, {
value: "two"
}];
// Build the object
var obj = {
"DataObject": {
"user": {
"-name": "username"
},
"contentFile": {
"-filename": "Breaking_News",
"lock": {
"-fileIsBeingEdited": "false"
},
"content": {
"line": []
}
}
}
};
var line = obj.DataObject.contentFile.content.line;
elem.forEach(function(entry, index) {
if (entry.value != '') {
line.push({
"-index": index,
"-text": entry.value
});
}
});
// Show result:
document.body.innerHTML =
"<pre>" +
JSON.stringify(obj, null, 2) +
"</pre>";
Side note: You don't check for blank strings like this:
if (!entry.value == '') { // <== Incorrect
You can use:
if (entry.value != '') {
or:
if (entry.value) {

You shouldn't build JSON like this, but use JSON.stringify() (see MDN doc) instead:
var myObject={foo:"bar"};
var myJSON=JSON.stringify(myObject);
console.log(myJSON); //echo {"foo":"bar"}

Here is an alternative way:
var json = {
iceteaDataObject: {
"-name": "hindsc52"
},
contentFile: {
"-filename": "Ticker",
lock: { "-fileIsBeingEdited": "false" },
content: {line: []}
}
}
for(var i = 0; i < elem.length; i++) {
if(!elem[i].value == '') {
json.contentFile.content.line.push({"-index": i,"-text": elem[i].value }
}
}
var jsonStr = JSON.stringify(json);

You need to put all your keys in quotes for this to work. As the others have pointed out though, you are not really supposed to do this.
If you still want to do it your way, try this:
var jsonStr = '{'
+ '"iceteaDataObject": {'
+ '"user": {"-name": "hindsc52"},'
+ '"contentFile": {'
+ '"-filename": "Ticker",'
+ '"lock": { "-fileIsBeingEdited": "false" },'
+ '"content": {'
+ '"line": ['
for(var i = 0; i < elem.length; i++) {
if(!elem[i].value == '') {
jsonStr += '{'
jsonStr += '"-index": ' + i + ',';
jsonStr += '"-text": ' + '"' + elem[i].value + '"';
jsonStr += '},'
}
}
jsonStr += ']}}}}';

Related

How to make variables optional while concatenation of string?

I am manipulating string to display in UI, Data is being dynamically with below code sometime i don't get header and details so how to make IHeader and IResponse optional for the string concatenation below.
if i dont have IHeader it will break at IHeader.id and throw exception i want to display whatever data is available to render.
main.js
const data = [{
id: "header",
name: "IHeader"
}, {
id: "param",
name: "IParams"
}, {
id: "details",
name: "IResponse"
}]
function buildText(data) {
var IParams;
var IResponse;
var IHeader;
for (var item of data) {
if (item.id === "param") {
IParams = item;
} else if (item.id === "header") {
IHeader = item;
} else if (item.id === "details") {
IResponse = item;
}
}
var text = '';
text += app + '.setConfig({\n' + "env:" + getEnv() + '\n});' + '\n\n';
text += 'let param:' + IParams.name + ' ' + '=' + '' + JSON.stringify(request, null, 4) + ';\n\n';
text += ref + '(' + 'param,(result:' + ' ' + '{' + '\n' + IHeader.id + ':' + IHeader.name + '\n' + IResponse.id + ':' + IResponse.name + '\n' + '})' + ' ' +
' => {\n console.log(result); \n});';
}
1 - You can try to create an object with empty values. That'll prevent the exception.
emptyObject = {id: ""} // more empty keys, if there is
IParam = (item.id === "param") ? item : emptyObject
2 - Or ignore that concatenation of the variable if undefined or null.
if (Iparam) {
// concatenation ..
}

Structuring display with indent JavaScript

I have input object that looks like this:
myObj = {
"Ob1": {
"myObjName": "A1",
"myObjType": "string",
"myObjOcc": "minOccurs="1""
"Ob2": {
"myObjName": "B1",
"myObjType": "string",
"myObjOcc": "minOccurs="1""
"Ob3": {
"myObjName": "C1",
"myObjType": "string",
"myObjOcc": "minOccurs="1""
}
}
}
"Ob4": {
"myObjName": "A2",
"myObjType": "string",
"myObjOcc": "minOccurs="1""
}
}
And I have to display the objects in xml schema way:
<xs:complexType name="A1" type="string" minOccurs="1">
<xs:complexType name="B1" type="string" minOccurs="1">
<xs:simpleType name="C1" type="string" minOccurs="1"/>
</complexType>
</complexType>
<xs:simpleType name="A2" type="string" minOccurs="1"/>
The idea is, if an object has child is a complexType if not, it's simpleType.
I have this code that is doing the printing, but if anyone can help me structure it with indent:
function isNestedObject(obj) {
for (var o in obj) {
if (isComplexType(o, obj)) {
return true;
}
}
}
function isComplexType(key, obj) {
return (typeof obj[key] === "object");
}
function xsdStructure(obj) {
var str = "",
properties = obj.properties;
if (isNestedObject(obj)) {
if (obj instanceof Array) {
for(var o in obj) {
xsdStructure(obj[o]);
}
}
str += "<xs:complexType name=\"" + obj.attrName + "\" type=\"" + obj.type + "\" " + obj.multiplicty + ">\n";
for (var key in obj) {
var arr = obj[key];
if (arr instanceof Array) {
for (var a in arr) {
str += xsdStructure(arr[a]);
}
}
}
str += "</xs:complexType>\n"
} else {
str = "<xs:simpleType name=\"" + obj.attrName + "\" type=\"" + obj.type + "\" " + obj.multiplicty + "/>\n";
}
return str;
}
function printing(myObj) {
var result = "";
for (var key in object) {
result += xsdStructure(object[key]);
}
result = '<xs:schema>\n'
+ result
+ '</xs:schema>';
return result;
}
It suppose to look like the above xml schema, but I can't use DOMParser so it has to be done manually.
Thanks in advance
I prepared fiddle for you. I had few things to mention for you. First, you should use the same attrs names among all you function which works with initial object. Ex: str += "<xs:complexType name=\"" + obj.myObjName + "\" type=\"" + obj.myObjType + "\" " + obj.myObjOcc + ">\n"; and NOT your str += "<xs:complexType name=\"" + obj.attrName + "\" type=\"" + obj.type + "\" " + obj.multiplicty + ">\n"; Also you will never get this condition true if (obj instanceof Array) because your obj doesn't contains arrays at all.

Trace on nested objects couchdb update handler

i need to edit nested objects with unique key's! in couhdb document, but i can't do it.
my doc structure:
{
"_id":"20",
"_rev":"rev",
tasks": {
"20.t01": {
"name": "test",
"status": [],
"tasks": {
"20.t01t01": {
"status": [
],
"name": "name",
"tasks": {
"20.t01t01t01": {
"status": [],
"name": "name",
"tasks": {
"20.t01t01t01t01": {
"name": "name",
"status": [],
"tasks": {
}
}
}
}
}
}
}
}
}
}
I nedd to push some objects into status array's.
The update handler function:
"status": function(doc, req) {
var data = JSON.parse(req.body);
var value = data.value;
var path = data.path;
var message = 'set ' + path + ' status ' + value;
var pathar = path.split(".");
var level;
var body = doc;
var evalstr = "body.";
if (pathar[1].length > 2) {
level = (pathar[1].length) / 3;
for (var i = 1; i <= level - 1; i++) {
evalstr += "tasks[\"" + pathar[0] + "." + pathar[1].substring(0, i * 3) + "\"].";
}
evalstr += "tasks[\"" + pathar[0] + "." + pathar[1] + "\"].status.push(" + JSON.stringify(value) + ");";
} else {
level = 1;
evalstr += "tasks[\"" + pathar[0] + "." + pathar[1] + "\"].status.push(" + JSON.stringify(value) + ");";
}
eval([evalstr]);
doc = body;
//doc.tasks["20.t01"].tasks["20.t01t01"].status.push(value);
return [doc, JSON.stringify({
reg: evalstr,
doc: body
})];
}
how i write the design document update function for this structure in couchdb?
Tanks!

How do I get values from an array?

I have an array which is in the following format:
RBS: [ {
"RegExp": "",
"Type": ""
} ],
PAN: [ {
"RegExp": "Date",
"Type": "Date"
} ]
Now I want to pass the value PAN to a method and it should get the count of PAN length 1 and get PAN of regex values and type value. How can I do this? I formed an array like this: Name holds RBS and PAN:
var Regexp = [];
RegExpr.push(Name + ":" + Regexp);
function Check(test) {
//test will be RBS /PAN
}
var obj = {
RBS:[{"RegExp":"","Type":""}],
PAN:[{"RegExp":"Date","Type":"Date"}]
};
function getTypeAndValue( obj, value )
{
var output;
var keys = Object.keys( obj );
if ( obj [value ] )
{
output = obj[ value ][ 0 ];
}
return output;
}
var value = getTypeAndValue( obj, "PAN" );
if ( value )
{
console.log( "type is " + value.Type + " and RegExp is " + value.RegExp );
}
else
{
console.log( "this value doesn't exists" );
}
You mean something like this?
HTML
<div id="count"></div>
<div id="detail"></div>
JAVASCRIPT
var countEl = document.getElementById("count");
var detailEl = document.getElementById("detail");
function Check(test){
var count = test.length;
countEl.innerHTML = "Count: " + count;
detailEl.innerHTML = "";
for (var i = 0 ; i < count ; i++){
var values = test[i];
detailEl.innerHTML +=
"<br/>" + (i +1) + ":<br/>" +
"RegExp: " + values["RegExp"] + "<br/>" +
"Type: " + values["Type"] + "<br/>";
}
}
var Name = {
RBS: [ {
"RegExp": "",
"Type": ""
} ],
PAN: [ {
"RegExp": "Date",
"Type": "Date"
} ]
};
Check(Name.PAN);
DEMO
Here's a JSFiddle.

JSON parsing in javascript

I'm trying to parse JSON in JavaScript. If my JSON data looks like below, I want to iterate through all the JSON elements that start with "custom" and not with any other string. How do I do this?
{
"fields": {
"custom12": {
value: "dsada"
},
"custom45": {
value: "adsadad"
},
"test12": {
value: "12323"
}
}
}​
var newObject = {}, key;
for(key in data.fields){
if(key.search(/custom/) > -1){
newObject[key] = data.fields[key];
}
}
console.log(newObject);
The following iterates the properties of the fields object and checks whether the property's name contains custom:
var data = yourObjectLiteral, i, current;
for(i in data.fields) {
if(i.indexOf('custom') > -1) {
current = data.fields[i];
// ... your logic ...
}
}
With the json string you provided I'd do it as such:
<script src="json2.js"></script>
<script>
var raw = '{'
+ ' "fields": {'
+ ' "custom12": {'
+ ' "value": "dsada"'
+ ' },'
+ ' "custom45": {'
+ ' "value": "adsadad"'
+ ' },'
+ ' "test12": {'
+ ' "value": "12323"'
+ ' }'
+ ' }'
+ '}';
var data = JSON.parse(raw);
var fields = data.fields;
var message = '';
for (var key in fields) {
if (key.indexOf('custom') === 0) {
message += key + ': ' + fields[key].value + '\n';
}
}
alert(message);
</script>
But, if you can rewrite the incomming message a little it will look simpler.
<script src="json2.js"></script>
<script>
var raw = '{'
+ ' "custom12": "dsada",'
+ ' "custom45": "adsadad",'
+ ' "test12": "12323"'
+ '}';
var fields = JSON.parse(raw);
var message = '';
for (var key in fields) {
if (key.indexOf('custom') === 0) {
message += key + ': ' + fields[key] + '\n';
}
}
alert(message);
</script>

Categories

Resources