The server returns me a JSON string like this:
{"payload":{"data":"{\"notification_type\":\"{\"type1\":\"{\"type2\":\"type2 value\"}\"}\"}"}}
This string, as I understand, cannot be parsed with JSON.parse() API because the nested JSON strings within the string should be properly escaped. If the string is not properly escaped I get the below error:
Uncaught SyntaxError: Unexpected token n in JSON at position 22
So, the string should be properly escaped respecting the nested nature like below so that JSON.parse() can process it:
var properString = "{\"payload\":{\"data\":\"{\\\"notification_type\\\":\\\"{\\\\\\\"InternalKey\\\\\\\":\\\\\\\"InternalValue\\\\\\\"}\\\"}\"}}";
console.log("Proper String = ");
console.log(properString);
var firstLevelObject = JSON.parse(properString);
console.log("First Level Object = ");
console.log(firstLevelObject);
var secondLevelObject = JSON.parse (firstLevelObject.payload.data);
console.log("Second Level Object = ");
console.log(secondLevelObject);
var thirdLevelObject = JSON.parse(secondLevelObject.notification_type);
console.log("Third Level Object = ");
console.log(thirdLevelObject);
This is how google chrome's console outputs the same:
I however am unable to convert the improper string from server to properly escaped string as defined in the variable properString so that the JSON is properly constructed which can be traversable. How can the string be converted with proper escape characters?
Reference sources:
I have referred to this answer to understand how nested escape characters should be added, but the answer does not state how conversion can be done.
Actually, the JSON string what you get is not exactly right. It's not a right JSON syntax in the nested JSON String. But you can rebuilt it to a correct JSON syntax string via regular expression or native JS.
var obj = '{"payload":{"data":"{\"notification_type\":\"{\"type1\":\"{\"type2\":\"type2 value\"}\"}\"}"}}';
var payloadString = obj.substring(0, 20).concat('"}}');
obj = obj.substring(20, obj.length - 3).replace("\"{", "{").replace("}\"}", "}}").replace("}\"}", "}}").replace("\"{", "{");
var data = JSON.parse(obj);
var obj2 = JSON.parse(payloadString);
//console.log(payload);
//console.log(data);
obj2.payload.data = data;
console.log(obj2);
I'm trying to save a string which is encoded as json into another json string.
In particular, I have to be able to handle empty objects: "{}".
PHP:
$sVal = "{}";
$jsonString = "{\"Var2\":\"My first var\", \"Var2\":\"My second var\", \"MyBlankObject\":\"{}\"}"
...
Javascript:
var oMyJSON = JSON.parse('< ?= $jsonString;? >');
I get a JSON parse error saying an unexpected { was found.
I can see the code in Chrome's debugger.
The brackets are simply removed and in the client side (javascript ) code, the object is replaced with the word null. That's not valid JSON.
,"Properties":null,
This causes javascript to crash.
If I try to json_encode it on the server side (PHP) I get double quotes on each side of the brackets.
,"Properties":""{}"",
I get the same thing if I just add the double quotes: ""{}""
Of course, this causes javascript to crash too.
Once in the client and I have the JSON object intact, I need to be able to extract the 'string' held in the property: MyBlankObject and then decode that JSON into a seperate JSON object.
Everything I've tried fails. How can I accomplish this?
You can define the object using PHP notation, and let json_encode encode it for you.
$phpArray = [
'Var2' => 'My first var',
'Var2' => 'My second var',
'MyBlankObject' => new \stdClass
];
And then in the JavaScript:
var oMyJSON = JSON.parse('<?= json_encode($phpArray); ?>');
I have created an SQL database using PHPmyAdmin which stores JSON files, the idea is to use these files with the Google Maps API to place markers on a map.
I am having trouble converting the JSON file to a JavaScript Object.
after retrieving the json from the database and converting it to a JS format, i assigned it to a variable.
For display purposes I have shown the way I get the String from PHP:
var jsonString ='<?php echo implode(" ", $firstJsonString); ?>'
As well as the actual string:
var jsonString = '{"address_components":[{"long_name":"London","short_name":"London","types":["locality","political"]},{"long_name":"London","short_name":"London","types":["postal_town"]},{"long_name":"Greater London","short_name":"Greater London","types":["administrative_area_level_2","political"]},{"long_name":"England","short_name":"England","types":["administrative_area_level_1","political"]},{"long_name":"United Kingdom","short_name":"GB","types":["country","political"]}],"adr_address":"<span class="locality">London</span>, <span class="country-name">UK</span>","formatted_address":"London, UK","geometry":{"location":{"lat":51.5073509,"lng":-0.12775829999998223},"viewport":{"south":51.38494009999999,"west":-0.351468299999965,"north":51.6723432,"east":0.14827100000002247}},"icon":"https://maps.gstatic.com/mapfiles/place_api/icons/geocode-71.png","id":"b1a8b96daab5065cf4a08f953e577c34cdf769c0","name":"London","photos":[{"height":800,"html_attributions":["Edu Sousa"],"width":1200},{"height":1065,"html_attributions":["Manuel Ligabue"],"width":1600},{"height":1365,"html_attributions":["David Sun"],"width":2048},{"height":2136,"html_attributions":["Nuno Martins"],"width":3216},{"height":3000,"html_attributions":["Roberto Gerosa"],"width":4000},{"height":3024,"html_attributions":["ALLWYN D'SILVA"],"width":4032},{"height":1080,"html_attributions":["Cristina Cunsolo"],"width":1920},{"height":1362,"html_attributions":["Dendy Legends"],"width":2048},{"height":1440,"html_attributions":["Destiny Symonee"],"width":2560},{"height":1452,"html_attributions":["Leslie"],"width":5248}],"place_id":"ChIJdd4hrwug2EcRmSrV3Vo6llI","reference":"CmRbAAAAw49v9euZCWzrvjJ9b8STdg4qK48YueqQIOMerhQ43OP-NynPqFygwZnFzb-jcKkRKJog7z2IeUubF468akLhMj7pIZSoOWFXGjKC0WgkubgTIRlySRkBM47V9RMcX5YoEhB3qYHCQ3roB1G_gHnh_i8MGhSbxmofinNGCLquqddTEQ3DjsKOcg","scope":"GOOGLE","types":["locality","political"],"url":"https://maps.google.com/?q=London,+UK&ftid=0x47d8a00baf21de75:0x52963a5addd52a99","utc_offset":60,"vicinity":"London","html_attributions":[]} {"address_components":[{"long_name":"London","short_name":"London","types":["locality","political"]},{"long_name":"London","short_name":"London","types":["postal_town"]},{"long_name":"Greater London","short_name":"Greater London","types":["administrative_area_level_2","political"]},{"long_name":"England","short_name":"England","types":["administrative_area_level_1","political"]},{"long_name":"United Kingdom","short_name":"GB","types":["country","political"]}],"adr_address":"<span class="locality">London</span>, <span class="country-name">UK</span>","formatted_address":"London, UK","geometry":{"location":{"lat":51.5073509,"lng":-0.12775829999998223},"viewport":{"south":51.38494009999999,"west":-0.351468299999965,"north":51.6723432,"east":0.14827100000002247}},"icon":"https://maps.gstatic.com/mapfiles/place_api/icons/geocode-71.png","id":"b1a8b96daab5065cf4a08f953e577c34cdf769c0","name":"London","photos":[{"height":800,"html_attributions":["Edu Sousa"],"width":1200},{"height":1065,"html_attributions":["Manuel Ligabue"],"width":1600},{"height":1365,"html_attributions":["David Sun"],"width":2048},{"height":2136,"html_attributions":["Nuno Martins"],"width":3216},{"height":3000,"html_attributions":["Roberto Gerosa"],"width":4000},{"height":3024,"html_attributions":["ALLWYN D'SILVA"],"width":4032},{"height":1080,"html_attributions":["Cristina Cunsolo"],"width":1920},{"height":1362,"html_attributions":["Dendy Legends"],"width":2048},{"height":1440,"html_attributions":["Destiny Symonee"],"width":2560},{"height":1452,"html_attributions":["Leslie"],"width":5248}],"place_id":"ChIJdd4hrwug2EcRmSrV3Vo6llI","reference":"CmRbAAAAw49v9euZCWzrvjJ9b8STdg4qK48YueqQIOMerhQ43OP-NynPqFygwZnFzb-jcKkRKJog7z2IeUubF468akLhMj7pIZSoOWFXGjKC0WgkubgTIRlySRkBM47V9RMcX5YoEhB3qYHCQ3roB1G_gHnh_i8MGhSbxmofinNGCLquqddTEQ3DjsKOcg","scope":"GOOGLE","types":["locality","political"],"url":"https://maps.google.com/?q=London,+UK&ftid=0x47d8a00baf21de75:0x52963a5addd52a99","utc_offset":60,"vicinity":"London","html_attributions":[]}';
Here I attempt to convert it to an object:
var obj = JSON.parse(jsonString);
console.log(obj);
However when run I get an error:
Uncaught SyntaxError: Unexpected token l in JSON at position 492
I checked position 492, this is at the point where there is an '=' symbol.
Looking at it now, I believe this is the first occurence of an "=" symbol in this JSON string.
Why is this = symbol causing this error, and how can I prevent it?
Thanks!
You don't have to parse the JSON. JSON is a JavaScript Object Notation, so you can get rid of the strings and it will declare a JavaScript object for you to use.
You can use https://jsonlint.com to validate your JSON
Edit
Your JSON is incorrect. Near "adr_address": "<span class=" there is an error in your JSON. You should solve that first.
I'm confused as to how I should be using JSON objects within MVC and how they should passed from Controller, to View, to Jscript.
I'm also not sure if I'm correctly parsing the JSON objects at the right points...
My controller is returning a PartialView with a json object ("Variables" is a list of data e.g. Id=2012, Name=BillyJoel, Value="£2,000"):
public ActionResult JavascriptConstants() {
var variables = Service.Obtain<VariableService>().All().ToList();
var json = new JavaScriptSerializer().Serialize(variables);
return PartialView("JavascriptConstants", json);
}
My View then makes this data available to my scripts by creating this variable:
#model string
...
var mvcListOfVariablesInDB = '#Html.Raw(Json.Encode(Model))';
My Jscript file then accesses the data and attempts to pull out the information and key value pairs, but seems to be interpreting the JSON as a string:
var variableList = $.parseJSON(mvcListOfVariablesInDB);
for (var variable in variableList) {
alert(variableList[variable]);
}
This just returns alerts of ", [, {, etc. as each character of the string is displayed. How do I access the key values of the JSON object?
I've tried changing my JS to use:
var variableList = $.parseJSON(mvcListOfVariablesInDB);
But this just gives me an Uncaught SyntaxError: Unexpected token I error in my browser (I'm assuming when it hits the "I" of "Id).
Any help much appreciated, thanks.
I found the issue:
The issue was the use of JavaScriptSerializer().Serialize(foo) as this was creating a JSON object that contained newlines and tabs instead of replacing them with \n and \t.
$.parseJSON() cannot handle newlines and so throws up unexpected token error.
This was corrected by importing the JSON.NET package and using :
var json = JsonConvert.SerializeObject(variables);
This passed a JSON object with newlines and tabs replaced with \n's and \t's. Which can then be made accessible to the View using:
#model string
...
var mvcListOfVariablesInDB = '#Html.Raw(Json.Encode(Model))';
and finally in the script using:
var variableList = $.parseJSON(mvcListOfVariablesInDB)
Hope this helps someone else one day...