convert an input value in array - javascript

I have this data in an input: [16,57.35], [23,56.26], [34,54.57]
and I want to turn it into an array
var data =$('#data').val();
var array = JSON.parse ("["+data+"]");
I'm having this error
Uncaught SyntaxError: Unexpected token.
How I can fix it or I can convert the input value in array?

Your code is working check it here, you may need to include required jQuery library or check some thing else in the code causing it.
data = $('#txt1').val();
arr = JSON.parse ("["+data+"]");
console.log(arr);

Try using the eval function:
var data = "123, 456, 789";
var array = eval("[" + data + "]");
You'll need to make sure that whatever you're inputting is valid JSON, but the above code will output an array for you. Hope it helps.

Related

Deserialize JSON string into array of list

I've a string
var my_str="[(0,10),(1,15),(2,48),(3,63),(4,25),(5,95),(6,41),(7,31),(8,5),(15,2)]";
I need to convert it into an array of list. For example,
alert(my_str[1])
would give an output of 1,15.
I've tried the following:
var myarray = JSON.parse(my_str);
but it throws the error "unexpected token ( in JSON at position 1"
I tried this
var myarray = JSON.parse(my_str);
but it throws error "unexpected token ( in JSON at position 1"
So I changed the structure of my string to:
var my_str="[[0,10],[1,15],[2,48],[3,63],[4,25],[5,95],[6,41],[7,31],[8,5],[15,2]]";
That worked like a charm ;)
The problem is that you are using a strange sintax for delimiting inner objects. It would be appropriate to use "[" and "]" instead of "(" and ")".
Anyway you can easily replace them with javascript and make your structure an array of arrays of strings. Sounds a bit creepy, but this way you can create a licit JSON object and benefit of JS native methods.
var my_array = JSON.parse(my_str.replace(/\(/g,'[').replace(/\)/g,']'))
you can now work on my_array object and retrieve couples of numbers using array indexes
my_array[1] ---> 1,15
You have to replace ( by '( and ) by )' ,, then , apply eval :
eval(arr.replace(/(/g,'\'(').replace(/)/g,')\''));
//> ["(0,10)", "(1,15)", "(2,48)", "(3,63)", "(4,25)", "(5,95)", "(6,41)", "(7,31)", "(8,5)", "(15,2)"]
This is a pretty naive idea, but does work (without JSON.parse or eval):
var arr = my_str.replace('[(', '').replace(')]', '').split('),(');
//> ["0,10", "1,15", "2,48", "3,63", "4,25", "5,95", "6,41", "7,31", "8,5", "15,2"]
var arr = my_str.split("),(")
arr[0] = arr[0].slice(2);
arr[arr.length-1] = arr[arr.length-1].slice(0,-2)

Get values from JSON returned data

So I have a function that makes an ajax call and returns a json string. I am having trouble trying to access the values that I need, below is my code of what I have and a few examples of what I have tried.
s.search().then(function (specials) {
var returnJSON = JSON.parse(specials[0]);
var x = returnJSON.location.x;
var y = returnJSON.location.y;
});
When I check the dev tools I'm getting the following error.
JSON.parse: unexpected character at line 1 column 2 of the JSON data
Here is the the JSON returned value after I stringify it.
[{"feature":{"geometry":{"type":"point","x":-82.9172080701955,"y":42.55426092899978,"spatialReference":{"wkid":102100,"latestWkid":3857}},"symbol":null,"attributes":{"Addr_type":"Postal","Match_addr":"48035, Clinton Township, Michigan","StAddr":"","City":"Clinton Township","score":100},"infoTemplate":null},"extent":{"type":"extent","xmin":-82.922209,"ymin":42.549261,"xmax":-82.912209,"ymax":42.559261,"spatialReference":{"wkid":102100,"latestWkid":3857}},"name":"48035, Clinton Township, Michigan"},{"feature":{"geometry":{"type":"point","x":-84.03589825899667,"y":44.826904141314174,"spatialReference":{"wkid":102100,"latestWkid":3857}},"symbol":null,"attributes":{"Addr_type":"Locality","Match_addr":"Clinton Twp, Michigan","StAddr":"","City":"Clinton Twp","score":100},"infoTemplate":null},"extent":{"type":"extent","xmin":-84.085899,"ymin":44.776904,"xmax":-83.985899,"ymax":44.876904,"spatialReference":{"wkid":102100,"latestWkid":3857}},"name":"Clinton Twp, Michigan"},{"feature":{"geometry":{"type":"point","x":-83.93987906956261,"y":42.065412162742234,"spatialReference":{"wkid":102100,"latestWkid":3857}},"symbol":null,"attributes":{"Addr_type":"Locality","Match_addr":"Clinton Twp, Michigan","StAddr":"","City":"Clinton Twp","score":100},"infoTemplate":null},"extent":{"type":"extent","xmin":-83.98988,"ymin":42.015412,"xmax":-83.88988,"ymax":42.115412,"spatialReference":{"wkid":102100,"latestWkid":3857}},"name":"Clinton Twp, Michigan"},{"feature":{"geometry":{"type":"point","x":-82.93354923650725,"y":42.60054198222781,"spatialReference":{"wkid":102100,"latestWkid":3857}},"symbol":null,"attributes":{"Addr_type":"Locality","Match_addr":"Clinton Twp, Michigan","StAddr":"","City":"Clinton Twp","score":100},"infoTemplate":null},"extent":{"type":"extent","xmin":-82.98355,"ymin":42.550542,"xmax":-82.88355,"ymax":42.650542,"spatialReference":{"wkid":102100,"latestWkid":3857}},"name":"Clinton Twp, Michigan"},{"feature":{"geometry":{"type":"point","x":-83.97095926895429,"y":42.07240087260328,"spatialReference":{"wkid":102100,"latestWkid":3857}},"symbol":null,"attributes":{"Addr_type":"Locality","Match_addr":"Clinton, Michigan","StAddr":"","City":"Clinton","score":94.29},"infoTemplate":null},"extent":{"type":"extent","xmin":-84.02096,"ymin":42.022401,"xmax":-83.92096,"ymax":42.122401,"spatialReference":{"wkid":102100,"latestWkid":3857}},"name":"Clinton, Michigan"},{"feature":{"geometry":{"type":"point","x":-84.6015125489642,"y":42.943655651388326,"spatialReference":{"wkid":102100,"latestWkid":3857}},"symbol":null,"attributes":{"Addr_type":"SubAdmin","Match_addr":"Clinton, Michigan","StAddr":"","City":"Clinton","score":94.29},"infoTemplate":null},"extent":{"type":"extent","xmin":-84.839514,"ymin":42.705656,"xmax":-84.363514,"ymax":43.181656,"spatialReference":{"wkid":102100,"latestWkid":3857}},"name":"Clinton, Michigan"}]
I am trying to access candidates location x value and y value.
There are some Strings in your JSON on separate lines. When you copy and paste your JSON in a linter (e.g.: json linter), you will see the errors.
EDIT:
You edited your question so you are now using valid JSON.
There is no need to parse your JSON when you already have valid JSON. You can just select the correct keys. Looking at your JSON, you can select your x and y like this:
var returnJSON = specials[0];
var x = returnJSON.feature.geometry.x;
var y = returnJSON.feature.geometry.y;
Checkout this codepen for an example.
You don't need to "parse" JSON returned from a service usually. It is already a Javascript object in the then callback.
s.search().then(function (specials) {
var firstItem = specials[0];
var x = firstItem.location.x;
var y = firstItem.location.y;
});
It should be noted, however, that the first item that comes back in your array of specials does not have a property location accoring to the JSON example you posted.
Perhaps you were after firstItem.feature.geometry.x, but im not sure.

Javascript: Push Json String to Json object

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)];

javascript String to JSON?

I have a string:
a = "{u'a':[u'123',u'321'], u'b':[u'456',u'654']}"
I want to convert this a to a json data.
How to do it?
I have tried JSON.parse(), but it will raise an error.
SyntaxError: Unexpected token u
That looks like Python literal syntax to me. Tell whoever wrote the Python portion to encode as JSON instead of just outputting the structure as a string.
In this particular case, you can just replace each u'x' with "x" and you'll have valid JSON:
var a = "{u'a':[u'123',u'321'], u'b':[u'456',u'654']}";
// Convert to JSON (May not work with other inputs!)
var json = a.replace(/u'((?:[^'\\]|\\.)*)'/g, function(a,str){
return '"' + str.replace(/\\'/g, '\'').replace(/"/g, '\\"') + '"';
});
// Parse the JSON into a Javascript object
var obj = JSON.parse(json);
Updated to work with some quotes in the object:
var a = "{u'a':[u'\\'123\\'',u'321'], u'b':[u'456\\\\',u'\"654\"']}";
Becomes:
{a:["'123'","321"], b:["456\",""654""]}
You need to change your input string to a valid JSON string.
I think this is what you wanted:
JSON.parse('{"a":["123","321"], "b":["456","654"]}')
The variables (keys / values ) are strings so need to be in quotes in order to be parsed as valid JSON.
// put quotes around the key / value pairs.
var a = "{\"u'a'\":[\"u'123'\",\"u'321'\"], \"u'b'\":[\"u'456'\",\"u'654'\"]}";
jQuery
a = $.parseJSON(a);
JSON is supposed to contain only strings.
a = "{u'a':[u'123',u'321'], u'b':[u'456',u'654']}"
Here I can only assume that u is a variable. Change it to this:
a = "{"+u+"'a':["+u+"'123',"+u+"'321'], "+u+"'b':["+u+"'456',"+u+"'654']}"

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