Link to home
Start Free TrialLog in
Avatar of ethar turky
ethar turkyFlag for Saudi Arabia

asked on

Generate Json using JS

Deal all,
The following code  generate json
var jsonfied = [{
		items : items.replace(/,$/, "").split("\n").map(function(item) {
                        var values = item.split(',');
			return {
				name : values[0],
                                column_type: values[1]
			};
		})
	}];

Open in new window

to parse this data :
FieldName01,typ1
FieldName02,typ2
FieldName03,typ3

Open in new window


I just need to change the js code to pares this data:
Tablename1:
FieldNameID,typ1
FieldName02,typ2
FieldName03,typ3
Tablename2:
FieldNameID,typ4
FieldName02,typ1
FieldName03,typ2

Open in new window

and generate the following json:
[{
      TableName: "TableName1" ,
      languages: [
      { name: "FieldNameID" , column_type:"typ1"  },
      { name: "FieldName02" , column_type:"typ2" },
      { name: "FieldName03" , column_type:"typ3"  },

      ],
},
{
      TableName: "TableName2" ,
      languages: [
      { name: "FieldNameID" , column_type:"typ4" },
      { name: "FieldName02" , column_type:"typ1" },
      { name: "FieldName03" , column_type:"typ2" },

      ]
}]

Open in new window

Avatar of Alexandre Simões
Alexandre Simões
Flag of Switzerland image

Hi mate, here it is: http://jsfiddle.net/VM3jc/3/
This time I didn't do it with the map because there's no way to properly split by the table name row.
So what I do is split by line and create a new item each time I find a line that ends with :


var items = 'Tablename1:\nFieldNameID,typ1\nFieldName02,typ2\nFieldName03,typ3\nTablename:\nFieldNameID,typ4\nFieldName02,typ1\nFieldName03,typ2';

var jsonfied = function(input) {
    var result = [];
    var lines = items.replace(/,$/, "").split("\n");
 
    var item = null;
    for (var i=0;i<lines.length;i++){
        if(lines[i].substr(-1) === ':'){
            if(item) result.push(item);
            item = { tableName: lines[i].split(':')[0], languages: [] };
        } else {
            var values = lines[i].split(',');
            item.languages.push({ name: values[0], column_type: values[1] });
        }
    }
    
    if(item) result.push(item);
    return result;
}

Open in new window

Avatar of ethar turky

ASKER

what is the useful of input here?
ASKER CERTIFIED SOLUTION
Avatar of Alexandre Simões
Alexandre Simões
Flag of Switzerland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ok, I just need to add [ and ] for whole result string ?