i have a json string returned to a hidden value and i want to assign it to a javascript array and print each element of the array.
Json string returned by hdn_client_windows - ["5703","5704"]
Javascript array assignment is as below.
var times = $('#hdn_client_windows').val();
alert(times[0]); // this printed only--> [
alert(times[1]); // this printed only--> "
what am i doing wrong ?
You need to parse the JSON into an array with JSON.parse first:
var times = JSON.parse($('#hdn_client_windows').val());
Since you are already using jQuery, it might be a good idea to defer to $.parseJSON instead just to be on the safe side (full compatibility with old browsers):
var times = $.parseJSON($('#hdn_client_windows').val());
Use $.parseJSON().
var str = '["5703","5704"]';
var times = $.parseJSON( str );
You have to parse the string first using JSON.parse (older browsers might require you to load this in):
var times = JSON.parse($('#hdn_client_windows').val());
alert(times[0]); // Will display first item
alert(times[1]); // Will display second item
You could use jquery's parseJSON() function.
var str = '["5703","5704"]';
var parsed = $.parseJSON( str );
The parsed object now contains the array: ["5703","5704"]
Reference - jQuery.parseJSON( json )
"Takes a well-formed JSON string and returns the resulting JavaScript object."
Related
I am looking for an easy way to trim left side from my json response and trim right side from my json output.
An example my json how it is:
{"something":[{"id":"1","name":"Test1"},{"id":"2","name":"Test2"},{"id":"3","name":"Test3"}]}
How i want it to be:
[{"id":"1","name":"Test1"},{"id":"2","name":"Test2"},{"id":"3","name":"Test3"}]
As you can see I wat TrimLeft all before [ and TrimRight alls behing ] and this is where I have my json response in:
function responseHandler(res) {
return res;
}
The easiest way to go would probably to just save this json to a variable and access the content of something similar like this:
var jsonOutput = {"something":[{"id":"1","name":"Test1"},{"id":"2","name":"Test2"},{"id":"3","name":"Test3"}]};
var something = jsonOutput.something;
console.log(something);
The output should be the expected json.
Edit 1
Referring to your edit I add another piece of code to come up to your solution.
function responseHandler(response) {
var result = response.something;
return result ;
}
This should give you the expected response.
Why would you want to to that? You can access everything in that json respone. However you can just use javascript string functions, for example:
var x = '{"something":[{"id":"1","name":"Test1"},{"id":"2","name":"Test2"},
{"id":"3","name":"Test3"}]}';
y = x.substr(x.indexOf("["),x.lastIndexOf("]")-x.indexOf("[")+1);
console.log(y);
if you your ({"something":) this content is fixed you can use below code.
<script>
var str = '{"something":[{"id":"1","name":"Test1"},{"id":"2","name":"Test2"},{"id":"3","name":"Test3"}]}';
str = str.substring(0, str.length - 1).replace('{"something":','');
console.log(str);
</script>
var obj={"something":[{"id":"1","name":"Test1"},{"id":"2","name":"Test2"},{"id":"3","name":"Test3"}]};
var str=String(obj);
var output=str.substr(x.indexOf("["),x.lastIndexOf("]")-x.indexOf("[")+1);
JSON.parse(output);
The String() function converts the value of an object to a string.
The indexOf() method returns the index within the calling String
object of the first occurrence of the specified value, starting the
search at fromIndex. Returns -1 if the value is not found.
The lastIndexOf() method returns the index within the calling String
object of the last occurrence of the specified value, searching
backwards from fromIndex. Returns -1 if the value is not found.
The JSON.parse() method parses a string as JSON, optionally
transforming the value produced by parsing.
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);
}
I'm currently processing some json encoded data, but I can't access it properly, this are some tests I did:
Code fragment 1:
var json = [
{"MarkerId":1,"0":1,"UserId":2147483647,"1":2147483647,"locX":51,"2":51,"LocY":4,"3":4},
{"MarkerId":2,"0":2,"UserId":2147483647,"1":2147483647,"locX":55,"2":55,"LocY":4,"3":4}];
console.log(json[0][0]);
outputs:
1
Code fragment 2:
var json2 = getCookie('markers');
console.log(json2[0][0]);
outputs:
[
Code fragment 3:
console.log(getCookie('markers'));
output:
[{"MarkerId":1,"0":1,"UserId":2147483647,"1":2147483647,"locX":51,"2":51,"LocY":4,"3":4},{"MarkerId":2,"0":2,"UserId":2147483647,"1":2147483647,"locX":55,"2":55,"LocY":4,"3":4}]
as you can see when I use the result from test 3 hardcoded I can access it fine, but when I use it only in code i get something diffrent
does anyone know how to do this?
Cookies only store strings. You need to use JSON.parse() to convert them back to an object. Also, the contents of json isn't JSON but a JAvaScript object (actually, an array).
var obj2 = JSON.parse(getCookie('markers') || '[]');
console.log(obj2[0][0]);
The || '[]' falls back to an empty array if the cookie is missing since an empty string or undefined wouldn't be valid JSON.
The getCookie('markers') returns string. The native javascript method JSON.parse(text[, reviver]) , parse a string as JSON.
var json2 = getCookie('markers');
if ( typeof(json2 ) == "string" ) {
json2 = JSON.parse( json2 );
}
Then try your code ..
I am encoding some model data into a html element like this:
#Html.Raw(Json.Encode(Model));
The json string returned looks like this:
{"TestList":[{"FrequencyType":"1X","GCDs":"585.6","Identifier":"6144","SeqNo":9306,"SeqNoSpecified":true,"TSeqNo":8314,"TSeqNoSpecified":true,"TestDescr":"HBsAg"},{"FrequencyType":"1X","GCDs":"585.6","Identifier":"6124","SeqNo":9295,"SeqNoSpecified":true,"TSeqNo":8315,"TSeqNoSpecified":true,"TestDescr":"HCV Ab"},{"FrequencyType":"1X","GCDs":"585.3","Identifier":"6","SeqNo":9729,"SeqNoSpecified":true,"TSeqNo":8309,"TSeqNoSpecified":true,"TestDescr":"HD Monthly LS"}],"Frequency":[{"Key":"ANNUAL","Value":"Annually"},{"Key":"BIMONTH","Value":"Bi-Monthly"},{"Key":"BIWEEK","Value":"Bi-Weekly"},{"Key":"MON","Value":"Monthly"},{"Key":"1X","Value":"One Time"},{"Key":"QTR","Value":"Quarterly"},{"Key":"SMAN","Value":"Semi-Annual"},{"Key":"WEEK","Value":"Weekly"}]};
When I try to parse this using JSON.parse, I get an error:
arrayTestList = [];
var jsonTestList = $('#TestList').text();
jsonTestList = JSON.stringify(jsonTestList);
arrayTestList = JSON.parse(jsonTestList);
alert(arrayTestList.TestList[0]); // <===== this line is failing
Unable to get value of the property '0': object is null or undefined
How do I convert this jsonTestList string into a javascript array so that I can access elements of arrayTestList properly?
Edit:
Sorry, I forgot to mention my edit. Basically above javascript code is inside a Partial View 2. The code where I am json encoding the model is in another Partial View 1. From P V 2, I cannot access the model object of P V 1, so I am just dumping the contents into a div tag, so that I can access this list TestList element.
Try removing this line:
jsonTestList = JSON.stringify(jsonTestList);
jsonTestList is already a JSON string
The issue is now resolved.
I was getting an invalid character, but couldn't immediately recognize which character it was that was causing the problem. I found that my JSON string isn't valid because of the trailing semicolon that was output by the Json.Encode method. I validated the JSON string # http://jsonlint.com.
Once I removed that semicolon, the json string is populated as a JavaScript array into arrayTestList object.
Now just this works, as mentioned in both the answers above, JSON.stringify is not needed.
var arrayTestList = [];
var jsonTestList = $('#TestList').text().replace(";","");
arrayTestList = JSON.parse(jsonTestList);
alert(arrayTestList.TestList[0]);
Why are you using Json.Encode? Also in your code, why are you writing redundant code first you are using JSON.stringify and the JSON.parse same object.
jsonTestList = JSON.stringify(jsonTestList);
arrayTestList = JSON.parse(jsonTestList);
As per my understanding just Html.Raw will work
In JavaScript
var jsonObject = #Html.Raw(Model.TestList); //Here you will get JavaScript Object
var jsonTestList = jsonObject.TestList;
Here is the JSON returned from my Server.
"[{"description":"A user","name":"test","type":"user"}]"
I want to remove the outer double quates. Which means I want the JSON as
[{"description":"A user","name":"test","type":"user"}]
How can I do this? Please help.
You want to turn the JSON into JS objects right? If so, you would do JSON.parse(json). If you need IE7 support, you have to include a polyfill for JSON as it's not supported in IE7<.
You can get the current JSON polyfill here: https://github.com/douglascrockford/JSON-js/blob/master/json2.js
As the response from the server is not valid JSON you have to request it as text, fix it, and parse it as JSON. Use dataType: 'text' in your options in the ajax call.
Use the substr method to cut of the first and last character:
data = data.substr(1, data.length - 2);
Then you can parse the JSON:
var obj = $.parseJSON(data);
To strip the first and last character from a string:
var fixed_string = string.substring(1, string.length - 1);
var str = '[{"description":"A user","name":"test","type":"user"}]';
var data = (new Function( "return " +s))();
console.log(f);
In your case response from server is a json string you have to convert it to json object
var str = '[{"description":"A user","name":"test","type":"user"}]';
str = eval('('+str+')');
console.log(str[0].name) //this will give test
Hope this helps.