Expect Object but get String when parsing JSON - javascript

I am trying to parse a simple JSON string using jQuery
var parsedJSON = $.parseJSON('{"graph_data": "{}"}');
I would expect typeof(parsedJSON.graph_data) to be an Object but instead it is returning string. What is the correct way to return an Object?

It should be like
var parsedJSON = $.parseJSON('{"graph_data": {}}');
console.log(typeof(parsedJSON.graph_data));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
no need of " for object, " is needed for defining string and object key. So it will treat as string here. For more about JSON structure and example visit http://www.json.org/.

try it.
var parsedJSON = $.parseJSON('{"graph_data": "{}"}');
console.log(parsedJSON.graph_data);

Related

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;

Convert JSON key value using RegExp

I receive a JSON string from a server call, in this form:
{"0":{"jpgN":"2","spread_value":"392.22","relevant_new":"text"},"1":{"jpgN":"1","spread_value":"395.28","relevant_new":"text"},"count":2}
Using RegExp, is there any way to replace the value of any key jpgN with the string "http://mydomain.com/keyValue.jpg" (eg "http://mydomain.com/2.jpg")?
Replace "jpgN":"([^"]+)" to "jpgN":"http://mydomain.com/$1.jpg".
But it's better to parse json and change values using your programming language.
Something like that ?
var json = {"0":{"jpgN":"2","spread_value":"392.22","relevant_new":"text"},"1":{"jpgN":"1","spread_value":"395.28","relevant_new":"text"},"count":2};
var s = JSON.stringify(json);
s.replace(/\"jpgN\":\"(\w+)\"/g, "\"jpgN\":\"http://mydomain.com/$1.jpg\"");

Can I use a variable to pass a json string?

This code works:
$(this).load($('.pageloadlabel', this).attr('href'), {category: 1});
This code doesn't work:
var data = '{category: 1}';
$(this).load($('.pageloadlabel', this).attr('href'), data);
The question is, how can I make it work?
Your data is not a Javascript object but a string, you can convert it to object by eval e.g.
data = eval('(' + data + ')');
but eval is considered dangerous, so better to parse string as JSON e.g.
data = JSON.parse(data)
For JSON lib you can use json2
It's not JSON, it's a javascript object.
var data = { category: 1 };
If you have a string, you would have to convert it to a object.
And notice that your string is not a valid JSON, see the link for more details.
Take out the quotes, the load function is expecting an object, not a string.
Have you tried to use eval() on data?
var data = '{category: 1}';
$(this).load($('.pageloadlabel', this).attr('href'), eval(data));

Categories