Javascript Trim left and right from a JSON response - javascript

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.

Related

How to convert json object to string and replace text

I would like to convert my json to a string then find and replace substrings like so using JQuery
var data = JSON.stringify(object).text();
data.text(data.replace("meat", "vegetables"));
console.log(data);
This gives me
JSON.stringify(...).text is not a function
How can I fix this.
JSON.stringify is already a text (string), that's what stringify means (turn to a string), just omit the .text():
var object = {"food":"meat","quantity":"10"}
var data = JSON.stringify(object); // this is a string
data = data.replace("meat", "vegetables");
console.log(data);
The method stringify returns string and the type string doesn't have the method text, so just update the first line to the following:
var data = JSON.stringify(object);
also update the second line with the following:
data = data.replace("meat", "vegetables");

Using Jquery to get numeric value which is in between "/" in link

I am trying to fetch numeric value from link like this.
Example link
/produkt/114664/bergans-of-norway-airojohka-jakke-herre
So I need to fetch 114664.
I have used following jquery code
jQuery(document).ready(function($) {
var outputv = $('.-thumbnail a').map(function() {
return this.href.replace(/[^\d]/g, '');
}).get();
console.log( outputv );
});
https://jsfiddle.net/a2qL5oyp/1/
The issue I am facing is that in some cases I have urls like this
/produkt/114664/bergans-of-norway-3airojohka-3jakke-herre
Here I have "3" inside text string, so in my code I am actually getting the output as "11466433" But I only need 114664
So is there any possibility i can get numeric values only after /produkt/ ?
If you know that the path structure of your link will always be like in your question, it's safe to do this:
var path = '/produkt/114664/bergans-of-norway-airojohka-jakke-herre';
var id = path.split('/')[2];
This splits the string up by '/' into an array, where you can easily reference your desired value from there.
If you want the numerical part after /produkt/ (without limitiation where that might be...) use a regular expression, match against the string:
var str = '/produkt/114664/bergans-of-norway-3airojohka-3jakke-herre';
alert(str.match(/\/produkt\/(\d+)/)[1])
(Note: In the real code you need to make sure .match() returned a valid array before accessing [1])

Javascript Object not working with Native javascript methods like match(), replace etc

Here is the issue:
I go this Code:
var str = {"Acc":10 , "adm_data":"Denied"};
When I do something like:
console.log(str.Acc.match(/[0-9]+/g)) // To Get the Integer Value from the "Acc" key
Firebug Screams:
TypeError: str.Acc.match is not a function
console.log(str.Acc.match(/[0-9]+/g));
See Image:
I always do something like:
var str = "Hello _10";
console.log(str.match(/[0-9]+/g)) // This Works
Why is the Object thingi not working?
PLEASE NOTE:
As mentioned by #Fabrício Matté. The issue was that I was trying to
pass an integer Value to the .match method which does not belong
to integers. The solution was to do what #kundan Karn Suggested. Something like:
str.Acc.toString().match(/[0-9]+/g)// Converting it first to string then match. It worked!
match function works with string. So convert it to string first
str.Acc.toString().match(/[0-9]+/g)
It works just fine: http://jsfiddle.net/nKHLy/
but in order to get rid of the error you might want to try:
var str = {"Acc":"Hello_10" , "adm_data":"Denied"};
console.log(String(str.Acc).match(/[0-9]+/g));
or
var str = {"Acc":"Hello_10" , "adm_data":"Denied"};
console.log(str.Acc.toString().match(/[0-9]+/g));
To know the difference between the 2 options, check: What's the difference between String(value) vs value.toString()

Json to string to javascript array

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."

How to properly decode a JSON string encoded using Html.Raw(Json.Encode(Model))?

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;

Categories