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
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'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
I have an initial array (users) with multiple (string and numeric) arrays therein:
var users = [
['User: 10792 - Jack',45.7546,-117.807,2,'/res/smR11.gif'], ['User: 11248 - John',38.0867,131.976,3,'/res/smR08.gif']
];
I have a string of data from our server in the current form of:
newData = "['User: 18469 - Gary',-33.9399732539481,151.164383805489,3,'/res/markerw.gif'],['User: 10020 - Robert',40.6437563454472,-73.7593346140851,6,'/res/smR10.gif']";
I erase all existing data with users.length = 0;
I then need to insert the newData into the users array.
NOTE: I can obviously modify the server data into any other format
that would be more suitable.
Any help would be greatly appreciated.
try something like this
var users = JSON.parse(newData);
Your newData string looks very similar to the javascript above it. How about this...
users = eval('[' + newData + ']');
[EDIT]
As Bergi, rajeshkakawat and StephenJames pointed out, eval will work but is less secure.
See: JSON.parse vs. eval()
I have a full string consisting of something like this [(data1.1)(data1.2)][(data2.1)(data2.1)]
Ive read you can do something smart with match function and regex. I want two arrays with the data loaded out of the parentheses.. How in earth do i do that? Please use my string as example.
I came up with this abomination:
var array = s.replace(/^\[|\]$/g,'').split('][').map(function(a){
return a.replace(/^\(|\)$/g,'').split(')(')
});
http://jsfiddle.net/8kLhc/
Also if you deliberately save or transmit data like this then you should really have a look at JSON or proper database design.
I wasn't entirely sure what you were after, but I'm assuming this
var what = '[(data1.1)(data1.2)][(data2.1)(data2.2)]',
have = [],
you = [],
tried = /\[\(([^)]*)\)\(([^)]*)\)\]/g;
what.replace(tried, function (use, brain, forthis) {
you.push((have.push(brain), forthis));
});
console.log(have, you);
// ["data1.1", "data2.1"] ["data1.2", "data2.2"]