I am trying to convert the below string value to JSON:
var yourmsg = '{"yourid":{"latlng":[123,456],"data":{"id":2345," name ":" basanta ","status":"Available"}}}';
Please help me out.
I am trying to convert the below string value to JSON:
var yourmsg = '{"yourid":{"latlng":[123,456],"data":{"id":2345," name ":" basanta ","status":"Available"}}}';
Please help me out.
All object keys need to be strings, you can't use yourid
as key without qoutation marks:
var yourmsg = '{"'+yourid + '":{"latlng")+:[' + yourlat + ','+ yourlng + '],"data":{"id":' + yourid +'," name ":" basanta ","status":"Available"}}}';
This is how you convert your string to a JSON object and write it to a file:
var yourmsg = '{"yourid":{"latlng":[123,456],"data":{"id":2345," name ":" basanta ","status":"Available"}}}';
yourmsg = JSON.parse(yourmsg); // converts the string to JSON object.
fs.writeFile('file.json', JSON.stringify(yourmsg, null, '\t')); // write to file with tabbed formatting.
Based on the original version of the question, I think what the OP really wanted was a way to create JavaScript objects based on three parameters (yourid, yourlat, yourlng
). The OP's attempt was to first create a parameterized string and then ask how to get an object out of it.
If so, here is a more elegant approach to skip straight to the object creation and avoid needing to create a string and the use JSON.parse()
:
http://jsbin.com/qebiti/edit?js,console
var msgFactory = (function () {
return function (id, lat, lng) {
//id, lat, lng must be numbers because strings need to be quoted
var msgObject = {};
msgObject[id] = {
latlng: [lat, lng],
data: {
id: id,
name: " basanta ",
status: "Available"
}
};
return msgObject;
};
}()),
yourid = 2345,
yourlat = 123,
yourlng = 456,
yourmsgObj = msgFactory(yourid, yourlat, yourlng);
console.log(JSON.stringify(yourmsgObj, null, 4));
The factory is based on the assumption (from the sample data in comments) that the parameters are all numbers. If strings are desired, then the factory should quote the strings.
The only tricky part was that yourid
was being used both as a name and a value in the resultant object. This seems to have been lost in the question edits.