I'm just starting to learn Javascript so my apologies if this is a stupid question.
Basically my issue is this:
Via an external form that I cannot change, I am receiving the following data.
var data = "{\"status\": \"created\", \"name\": \"mike\", \"roleName\": \"Signer\", \"emailSubject\": \"test\", \"email\": \"hellO#yahoo.com\", \"templateId\": \"0171502E-38F7-43A7-BA09-6FC1FDAB09C2\" }"
Before I can send the data via API, the documentation requires that I add an additional nested key (templateRoles) to wrap rolename, emailsubject, and email into a new array. The final results is suppose to look like this.
var data = "{\"status\": \"created\", \"name\": \"mike\", \"templateRoles\": [{ \"roleName\": \"Signer\", \"emailSubject\": \"test\", \"email\": \"hellO#yahoo.com\"}], \"templateId\": \"0171502E-38F7-43A7-BA09-6FC1FDAB09C2\"}"
For the life of me I cannot figure out how to do this. I've tried using splice and replace but either I am doing it wrong or that isn't the right approach. Any suggestions or pointers in the right direction would be greatly appreciated.
Thanks in advance.
Use JSON.parse(data) to convert your JSON string into an object. Then you can manipulate that object. Once you're done manipulating simply use JSON.stringify() to get a JSON string back.
Sample code:
var data = "{\"status\": \"created\", \"name\": \"mike\", \"templateId\": \"0171502E-38F7-43A7-BA09-6FC1FDAB09C2\", \"templateRoles\": [{ \"roleName\": \"Signer\", \"emailSubject\": \"test\", \"email\": \"hellO#yahoo.com\"}]}";
var jsonObj = JSON.parse(data);
jsonObj.templateRoles = "some roles here";
var newDataStr = JSON.stringify(jsonObj);
So your basic code would look like this. Make the JSON string a JavaScript object, then manipulate it as such. Afterwards you can use JSON.stringyfi to put back to a JSON string.
var jsonData = "{\"status\": \"created\", \"name\": \"mike\", \"templateId\": \"0171502E-38F7-43A7-BA09-6FC1FDAB09C2\", \"roleName\": \"Signer\", \"emailSubject\": \"test\", \"email\": \"hellO#yahoo.com\"}";
var parsedJson = JSON.parse(jsonData);
// now manipulate
parsedJson.newProperty = "hey there";
parsedJson.status = "not created";
As a side note, I don't think you can order the keys, so you can do whatever in terms of adding properties or functions. Never rely on the keys to be in order. And by key, I mean property of function name of the object. Objects are held in a dictionary type way where their keys hold information.
So:
parsedJson["created"]
Is the same as
parsedJson.created
You can conditionally add data depending on whether a key exists:
for (var key in parsedJson)
if (key === "someKey")
// do something
OR
if (parsedJson["someKey"] === undefined)
// do something
Related
I have this code:
var string = '{"items":[{"Desc":"Item1"},{"Desc":"Item2"}]}';
localStorage.setItem('added-items', JSON.stringify(string));
This code will use localStorage.
Here is now the code to get the stored data:
var retrievedObject = localStorage.getItem('added-items');
My problem now is, how can i get the size of the data items? answer must be 2.
How can i get the "Item1" and "Item2"?
I tried retrievedObject[0][0] but it is not working.
And how to add data on it?
so it will be
{"items":[{"Desc":"Item1"},{"Desc":"Item2"},{"Desc":"Item3"}]}
Can I use JSON.stringify?
var string = '{"items":[{"Desc":"Item1"},{"Desc":"Item2"}]}';
localStorage.setItem('added-items', JSON.stringify(string));
stringify means, take an object and return its presentation as a string.
What you have, is already a string and not a JSON object.
The opposite is JSON.parse which takes a string and turns it into an object.
Neither of them have anything to do with getting the size of an array. When properly coding JavaScript you almost never use JSON.parse or JSON.stringify. Only if serialization is explicitly wanted.
Use length for the size of the array:
var obj = {"items":[{"Desc":"Item1"},{"Desc":"Item2"},{"Desc":"Item3"}]}
console.debug(obj.items.length);
// THIS IS ALREADY STRINGIFIED
var string = '{"items":[{"Desc":"Item1"},{"Desc":"Item2"}]}';
// DO NOT STRINGIFY AGAIN WHEN WRITING TO LOCAL STORAGE
localStorage.setItem('added-items', string);
// READ STRING FROM LOCAL STORAGE
var retrievedObject = localStorage.getItem('added-items');
// CONVERT STRING TO REGULAR JS OBJECT
var parsedObject = JSON.parse(retrievedObject);
// ACCESS DATA
console.log(parsedObject.items[0].Desc);
To bring clarity to future people that may stumble across this question and found the accepted answer to not be everything you hoped and dreamed for:
I've extended the question so that the user may either want to input a string or JSON into localStorage.
Included are two functions, AddToLocalStorage(data) and GetFromLocalStorage(key).
With AddToLocalStorage(data), if your input is not a string (such as JSON), then it will be converted into one.
GetFromLocalStorage(key) retrieves the data from localStorage of said key
The end of the script shows an example of how to examine and alter the data within JSON. Because it is a combination of objects and array, one must use a combination of . and [] where they are applicable.
var string = '{"items":[{"Desc":"Item1"},{"Desc":"Item2"}]}';
var json = {"items":[{"Desc":"Item1"},{"Desc":"Item2"},{"firstName":"John"},{"lastName":"Smith"}]};
localStorage.setItem('added-items', AddToLocalStorage(string));
localStorage.setItem('added-items', AddToLocalStorage(json));
// this function converts JSON into string to be entered into localStorage
function AddToLocalStorage(data) {
if (typeof data != "string") {data = JSON.stringify(data);}
return data;
}
// this function gets string from localStorage and converts it into JSON
function GetFromLocalStorage(key) {
return JSON.parse(localStorage.getItem(key));
}
var myData = GetFromLocalStorage("added-items");
console.log(myData.items[2].firstName) // "John"
myData.items[2].firstName = ["John","Elizabeth"];
myData.items[2].lastName = ["Smith","Howard"];
console.log(myData.items[2]) // {"firstName":["John","Elizabeth"],"lastName":["Smith","Howard"]}
console.log(myData.items.length) // 4
JSON.parse is definitely the best way to create an object but I just want to add if that doesn't work (because of lack of support), obj = eval('(' + str + ')'); should work. I've had a problem with a HTML to PDF converter in the past that didn't include JSON.parse and eval did the trick. Try JSON.parse first.
Access your object: obj.items[0].Desc;
var object = Json.parse(retrievedObject);
Now you can access it just like an array
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
If you need more help i have some previous code where i am reading Json from local storage and making a form from that json. This code will help in understanding how to traverse that array
Json stored in localstorage
{"form":[{"element":"input", "type":"text","name":"name","value":"value","min":"2","max":"10"}]}
JavaScript to read that json
function readJson(){
if(!form_created){
add_form();
}
var fetched_json = localStorage.getItem("json");
var obj=JSON.parse(fetched_json);
for(var i=0; i<obj.form.length;i++){
var input = document.createElement(obj.form[i].element);
input.name = obj.form[i].name;
input.value = obj.form[i].value;
input.type = obj.form[i].type;
input.dataset.min = obj.form[i].min;
input.dataset.max = obj.form[i].max;
input.dataset.optional = obj.form[i].optional;
form.insertBefore (input,form.lastChild);
}
alert(obj.form[0].name);
}
Im trying to Push a valid json string to javascript json object, but every time im trying to do it like that:
markersData['values'] = [string];
the result is of markersData json object is:
"values":["{'latLng..."
instead of (Original):
"values":[{"latLng...
it take all of the json and push it as one variable (invalid json), how can i push it as a part of the original json?
any idea how to solve it?
Thank you!
You need to deserialise the JSON string before setting it to the property of the object:
markersData['values'] = [JSON.parse(yourJsonString)];
markersData['values'] = [JSON.parse(string)];
Hope this helps.. Read more about JSON.parse here
You need to parse the string first.
JSON.parse(addstringvar);
Code pen demo
var testObj = {};
var addString = '{"name": "test"}';
testObj.values = [JSON.parse(addString)];
You'll need to make sure you have a valid JSON. So below will show you how to create an easy JSON which will be valid for you to use
JSON Object:
var newObject = {};
newObject.Latlng = "ValueHere";
var jsonString = JSON.stringify(newObject);
// Check jsonString before you parse for pushing.
console.log(jsonString);
You will need to deserialise the JSON string before setting it to the
property of the object
like Rory McCrossan mentions in his answer
jsonString[value] = [JSON.parse(jsonString)];
I want to put a JSON object into a javascript variable as a sting in order to create a graph.
qm.createGraphData = function() {
$.post("ajax_getGraphDataWebsite ", function(json) {
qm.negativesData = json;
},"json");
qm.data = [{
"xScale":"ordinal",
"comp":[],
"main":[{
"className":".main.l1",
qm.negativesData},{
"className":".main.l2",
qm.negativesData}],
"type":"line-dotted",
"yScale":"linear"}];
}
the string value should be added to the "data" section. Now the object get's added but I need to add the string value to the variable like the sample below:
{"data":[{"x":"3283581","y":"2013-10-16"},{"x":"1512116","y":"2013-10-17"},{"x":"3967","y":"2013-10-18"},{"x":"1094","y":"2013-10-19"},{"x":"853","y":"2013-10-20"},{"x":"1205","y":"2013-10-21"},{"x":"2618700","y":"2013-10-22"},{"x":"3928291","y":"2013-10-23"},{"x":"3670318","y":"2013-10-24"},{"x":"3347369","y":"2013-10-25"},{"x":"2525573","y":"2013-10-26"},{"x":"3224612","y":"2013-10-27"},{"x":"3992964","y":"2013-10-28"},{"x":"3949904","y":"2013-10-29"},{"x":"3568618","y":"2013-10-30"},{"x":"3104696","y":"2013-10-31"},{"x":"3246932","y":"2013-11-01"},{"x":"2817758","y":"2013-11-02"},{"x":"3198856","y":"2013-11-03"},{"x":"3952957","y":"2013-11-04"},{"x":"3934173","y":"2013-11-05"},{"x":"3878718","y":"2013-11-06"},{"x":"3642822","y":"2013-11-07"},{"x":"3186096","y":"2013-11-08"}]}
This would generate the right graph for me. Does anyone know how to convert the json object into a string like above and to send it to the qm.negativesData variable?
// UPDATE
Now I've got the string with the qm.negativesData = JSON.stringify(json); solution
But my qm.negativesdata won't get added to the qm.data variable... i'm getting a console error SyntaxError: invalid property id
I suppose i'm not adding them the right way?
To convert a JSON object into a JSON string, you can try myObject.stringify(), JSON.stringify(myObject), or if you are using a library using the built in function of that library.
So, you could do something like: qm.negativesData = myObject.stringify()
Cheers
I have a JSON string below that is being stored as a var in JavaScript. I am trying to parse the pieces of the string into variables.
In particular, I need the address, postcode, region, and locality.
This JSON array is being stored as a JS var called "data"
Does anyone know how I can begin parsing out those things? Thank you all!
[{"address":"2801 Elliott Ave","category_ids":[347],"category_labels":[["Social","Food and
Dining","Restaurants"]],"country":"us","email":"kimd#thedussingroup.com","factual_id":"43cfe23
8-ae8e-469a-8592-a1edc8603051","fax":"(206) 448-
9252","latitude":47.615154,"locality":"Seattle","longitude":-122.353724,"name":"The Old
Spaghetti Factory","neighborhood":["Belltown","Downtown","Downtown
Seattle"],"postcode":"98121","region":"WA","tel":"(206) 441-
7724","website":"http:\/\/www.osf.com"}]
Appreciate the help!
You JSON is an array (since it's contained in [ and ]), so you need:
var data = JSON.parse('[{"addre....}]');
var address = data[0].address,
postcode = data[0].postcode;
and so on...
for(var i in data[0]){
window[i] = data[0][i];
}
alert(address);
You can do this using JSON.parse
var data= your json;
JSON.parse(data);
Update:
In your case you don'e even need to parse you can use directly like
console.log(data[0].address); //returns 2801 Elliott Ave
console.log(data[0].category_ids); //returns [347]
Check this JSFiddle
So basically I have this code:
var string = '{name: "bob", height: 4, weight: 145}';
I would like to know if it is possible to convert that string into an object.
so that I can use
string.name, string.height, and string.weight
(I am retrieving the string variable from a database so I cannot just remove the quotes and make it an object in the first place)
eval, as suggested by Igor, will certainly work but is vulnerable to attack.
Instead you could use a library to parse it for you. There are options in the following link:
Eval is evil... So what should I use instead?
It seems that your string is malformed. In order to work with JSON.parse or even jQuery.parseJSON methods, your keys must have speech marks (" ) around them, like so:
var str = '{"name": "bob", "height": 4, "weight": 145}';
var obj = JSON.parse(str);
You can test this by adding console.log(obj); as the final line. Here is my jsFiddle example.
So try to see if you can pull down the data from the server in the format I have suggested and it can then easily be parsed into a JavaScript object.
I would not use string for a variable name, but:
var obj = eval(string);
alert(obj.name);
or you can use jQuery.parseJSON: api.jquery.com/jQuery.parseJSON.