Parse Json object - json

I have a following Json object:
data = [{"$id":"1","ID":2,"Name":"Exceptional trip to ZG"}]
I need to parse it so I can display individual attributes on my webpage.
I tried using this code:
var lang = '';
var obj = $.parseJSON(data);
$.each(obj, function() {
lang += this['ID'] + "<br/>";
});
$("#mybox1").html(lang);
but it doesn't work as $.parseJSON expects Json string like this one:
[{"$id":"1","ID":2,"Name":"Exceptional trip to ZG"}] - same only with quotation marks around it. This code works perfectly with Json string.

Why are you trying to parse? It's already a valid object. Check this fiddle.
This will accomplish your task:
var data = [{
"$id": "1",
"ID": 2,
"Name": "Exceptional trip to ZG"
}];
var lang = '';
$.each(data, function () {
lang += this['ID'] + "<br/>";
});
$("#mybox1").val(lang);

Related

How to parse unstructured JSON file in Node?

I have to parse a JSON file that has many objects but no structure to the file. It looks like this:
{"obj1": "john"}
{"obj2": "sally"}
{"obj3": "veronica"}
Each object is on on it's own there is no container. So when I open the file and try to iterate through it I get the error Unexpected token { in JSON
Aside from wrapping the objects in an array and then manually going through the whole file to add commas, how can I parse this?
If it's really one-object-per-line, it's fairly straightforward to take the string, break it into lines, and JSON.parse each line:
const str =
'{"obj1": "john"}\n' +
'{"obj2": "sally"}\n' +
'{"obj3": "veronica"}';
const array = str.split(/[\r\n]+/)
.map(entry => JSON.parse(entry));
console.log(array);
...but that's assuming it really is one object per line.
If you're reading the file, you don't have to start out with all in one string as above; just read line by line as Kevin B points out.
(Since you're using Node, I've happily used ES2015+ features above...)
If you assume each line of the input file is complete, self-standing JSON, then a split-into-lines-then-parse-each strategy works well.
But even if the data isn't limited to a single line, not all is lost. You can heuristically parse the file. It isn't hyper-efficient, but except for very large files you'll probably never know the difference:
function incrementallyParseJSON(filepath) {
var lines = fs.readFileSync(filepath)
.toString()
.split(/\n/g);
var result = [];
var [start, stop] = [0, 1];
while (stop <= lines.length) {
try {
var part = JSON.parse(lines.slice(start, stop).join('\n'));
result.push(part);
[start, stop] = [stop, stop+1];
} catch (e) {
stop += 1;
}
}
return result;
}
So if your file is:
{"obj1": "john"}
{"obj2": "sally",
"more": "other"}
{"obj3": "veronica"}
"something"
12
The result will be:
[ { obj1: 'john' },
{ obj2: 'sally', more: 'other' },
{ obj3: 'veronica' },
'something',
12 ]
Example:
function incrementallyParseJSON(str) {
var lines = str.split(/\n/g);
var result = [];
var [start, stop] = [0, 1];
while (stop <= lines.length) {
try {
var part = JSON.parse(lines.slice(start, stop).join('\n'));
result.push(part);
[start, stop] = [stop, stop+1];
} catch (e) {
stop += 1;
}
}
return result;
}
var str =
'{"obj1": "john"}\n' +
'{"obj2": "sally",\n' +
' "more": "other"}\n' +
'{"obj3": "veronica"}\n' +
'"something"\n' +
'12';
console.log(incrementallyParseJSON(str));

How to access json nested objects in node.js

I have used xml2js parser to parse the xml file in node.js. It is parsing the xml successfully. But now i want to parse the json or to identify the particular data in json.
My node.js code
var fs = require('fs');
var parseString = require('xml2js').parseString;
var xml = 'C:\\temp\\Masters.xml';
var fileData = fs.readFileSync(xml,'utf8');
parseString(fileData, function (err, result) {
console.log(JSON.stringify(result));
var json = JSON.stringify(result);
var jsonObj = JSON.parse(json);
for (var key in jsonObj) {
console.dir(key + ": " + jsonObj[key].Customer_Name);
}
});
In console output:
'Masters: undefined'
Json data:
'{"Masters":
{
"Customer":
[
{"Customer_Name":["Kim"],
"Customer_Code":["c86"],
"Date":["23-11-15"],
"Address":["Narhe"],
"City":["Pune"],
"State":["Maharashtra"],
"TIN":["3365670"],
"PAN_Number":["AAAAA1111a"],
"Mobile_Number":["8999000090"],
"Email_ID":["amitshirke#gmail.com"],
"Contact_Person":["Anish"],
"Opening_Balance":["0"] },
{"Customer_Name":["Ankit"],
"Customer_Code":["c87"],
"Date":["12-04-15"],
"Address":["Narhe"],
"City":["Pune"],
"State":["Maharashtra"],
"TIN":["336567"],
"PAN_Number":["AAAAA1111p"],
"Mobile_Number":["8900000000"],
"Email_ID":["amitshirke1#gmail.com"],
"Contact_Person":["Anuj"],
"Opening_Balance":["0"] }
]
}
}'
In above data, Masters is root element(Object), Customer is another nested object and there two customers. Then how can I access the customer names or how to use the for loop to access the same?.
Thanks in advance.
You can access the Customer array as follows -
var customerArray = Masters.Customer,
length = customerArray.length;
for(var i = 0; i < length; i++)
{
// You can access the customers array from here -
console.log(customerArray[i].Customer_Name[0]); // [0] hardcoded because as you can see all the variables are in array at 0th position
// similarly you can access other data
console.log(customerArray[i].City[0]);
}

Convert a javascript array to specific json format

I have this JSON.stringify(array) result: ["id:1x,price:150","id:2x,price:200"] and I have to convert it in a json format similar to this (it would be sent to php):
[{
"id":"1x",
"price":150
},
{
"id":"2x",
"price":200
}]
Please help.
You can convert the structure of your data before using JSON.stringify, for example you can convert the data to a list of objects like so:
var strItems = ["id:1x,price:150", "id:2x,price:200"];
var objItems = [];
for (var i = 0; i < strItems.length; i++) {
var pairs = strItems[i].split(",");
objItems.push({
id: pairs[0].split(':')[1],
price: parseInt(pairs[1].split(':')[1])
});
}
Before calling JSON.stringify to get the result you're after:
var json = JSON.stringify(objItems);
console.log(json);
JSON.stringify(array) only does on layer, but you can change the stringify function to work for multiple layers with this function written by JVE999 on this post:
(function(){
// Convert array to object
var convArrToObj = function(array){
var thisEleObj = new Object();
if(typeof array == "object"){
for(var i in array){
var thisEle = convArrToObj(array[i]);
thisEleObj[i] = thisEle;
}
}else {
thisEleObj = array;
}
return thisEleObj;
};
var oldJSONStringify = JSON.stringify;
JSON.stringify = function(input){
if(oldJSONStringify(input) == '[]')
return oldJSONStringify(convArrToObj(input));
else
return oldJSONStringify(input);
};
})();
Once you have declared this, then you can call JSON.stringify(array)

Unnesting json object

My sample json is
"multiList": [
{
"my_key" : "this is my key"
},
{
"my_text_box": "This is my text box"
},
]
How do I convert this to
{"my_key" : "this is my key"},
{my_text_box": "This is my text box"},
dynamically?
using jquery
Your question doesn't make sense. Are you asking to convert to two separate objects? A string representation of those two objects? Something else? I can do the first two:
var objOne = json.multiList[0];
var objTwo = json.multiList[1];
var objStr = JSON.stringify(json.multiList[0]) + ', '
+ JSON.stringify(json.multiList[1]);
If you want to add all of the separate properties into one object, you can just extend another object in a loop.
var obj = {};
json.multiList.forEach(function (elem) {
for (k in elem) {
if (elem.hasOwnProperty(k)) {
obj[k] = elem[k];
}
}
});
http://jsfiddle.net/ExplosionPIlls/t2xyd/
This makes no consideration for the overriding of properties in obj.

Parsing and formatting JSON date variable

I am parsing a JSON object with JavaScript and displaying it in a styled HTML table.
The date variable comes as a long string. (e.g. 2011-11-23 10:21:49.695805)
How can I format the date so as to be displayed: year-month-day, hour-minute instead of 2011-11-23 10:21?
The AJAX call:
$$.ajax({
url: '/ajax/myfolder',
dataType:"json",
success: function(json) {
$$('#JsonGrid').append(CreateTableView(json, "jsonFeed", true)).fadeIn();
parseDate();
}
});
function parseDate() {
}
The json object:
[{"status": "success", "date": "2011-11-23 10:21:49.695805", "user": "xy", "jobname": "jobnamexyz"}]
You can use date functions, DateJS, etc., but if the format is fixed as in your example you can just take the first sixteen characters:
var date = json["date"].substr(0,16);
EDIT: sorry, just noticed you wanted a comma in there. So:
var date = json["date"].substr(0,10) + ", " + json["date"].substr(11,5);
EDIT 2: OK, try moving the call to parseDate() to before you call CreateTableView(), so you can "fix" the data before it is used. The following assumes the json is an array of objects:
success: function(json) {
parseDate(json);
$$('#JsonGrid').append(CreateTableView(json, "jsonFeed", true)).fadeIn();
function parseDate(data) {
for (var i=0; i<data.length; i++)
if (data[i]["date"])
data[i]["date"] = data[i]["date"].substr(0,10)
+ ", " + data[i]["date"].substr(11,5);
}
You can use String.match method to parse the parts of string like "2011-11-23 10:21:49.695805". For example the code
var regexp = "([0-9]{4})(-([0-9]{2})(-([0-9]{2})" +
"([T| ]([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?" +
"(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?";
var dateString = "2011-11-23 10:21:49.695805";
var d = dateString.match(new RegExp(regexp));
will initialize d as array where d[1], d[3], d[5], d[7], d[8] and d[10] are year (2011), month (11), day (23), hour (10), minutes (21), seconds (49). The d[12] will be 695805 and only the first tree digits of it are milliseconds. So you can either create a Date like
var date = new Date(d[1],d[3],d[5],d[7],d[8],d[10],d[12].substr(0,3));
or display the parsed date as another string in any other format which you prefer.
$$.ajax({
url: '/ajax/myfolder',
dataType:"json",
success: function(json) {
$$('#JsonGrid').append(CreateTableView(json, "jsonFeed", true)).fadeIn();
parseDate(json);
}
});
function parseDate(json) {
var arr = json["date"].split(/:/);
var date = arr[0] + ":"+arr[1];
alert(date);
return date;
}
Maybe this jQuery extension can help you out: http://momentjs.com/
Like:
var now = moment();
var formatted = now.format('dddd, MMMM Do YYYY');