While assigning JSON in blade produces a JavaScript syntax error. There is two different cases:
First Case
var jsonString = {!! $json !!}; //it produce syntax error
It produce syntax error in some cases
Second Case
var jsonString = JSON.parse("{!! $json !!}");
It produce error while null or empty
Unexpected end of JSON input
Is there any way that handle both situations?
var jsonString = JSON.parse("{!! json_encode($json) !!}");
It is working for me.
Please try like this -
var json_res = "{{$json}}";
var jsonString = JSON.parse(json_res);
Hope this will help you.
You can achieve this using this way:
var json = null;
try {
var json = JSON.parse('<?=str_replace('\'','\\\'', $json);?>');
} catch(SyntaxError) {
// Do something If the json string is not a valid json.
}
Related
I am hitting a test API I built with jQuery which gives me a JSON.
In my Javascript, I am doing the following:
var myjson = (getData['responseJSON']['results']);
console.log(myjson);
This yields the below results:
{"A":{"0":1,"1":2},"B":{"0":2,"1":3},"C":{"0":3,"1":4}}
I would like to instead just return the values for A, which I assumed would just be like below. But when I do this I get undefined. What am I doing wrong here?
var myjson = (getData['responseJSON']['results']['A']);
console.log(myjson);
var myjson = JSON.parse(getData['responseJSON']['results']);
console.log(myjson['A']);
I try to display data in angularjs via json data array but can't figure out or fix the issue when i return the json data from my php file it give me result
["{name:'abc', age:19}","{name:'xyz', age:21}"]
but its not working because in Angular i need data in format something like this
[{name:'abc', age:19},{name:'xyz', age:21}]
now issue is i can't figure out how can i rearrange this array format i tried JSON.parse() but its not working
its my php code
if($xml->product) {
foreach ($xml->product as $node ){
$productName = $node->name;
$productID = $node->productID;
$productPrice = $node->price;
$productURL = $node->imageURL;
$productCat = $node->categories->category;
//$product = "{name: '".$productName."', productid: '".$productID."' }";
$product = array("name"=> "".$productName."", "productid"=> "".$productID."");
array_push($data1, $product);
}} else {
echo "error!"; } print json_encode($data1);
problem fixed actually i am passing string in array and then encode with json it give me this double quote issue. now what i fix is change string in array and passed by json it automatically convert these array in object :)
its fixed by changing string into array
$product = "{name: '".$productName."', productid: '".$productID."' }";
replace with this
$product = array("name"=> "".$productName."", "productid"=> "".$productID."");
var var1 = JSON.parse('[{"ItemId":1, "ItemName":"item 1\"", "Unit":"Nos","Remarks":null, "ConsumedQuantity":1.00},
{"ItemId":1253, "ItemName":"item 2", "Unit":"Nos", "Remarks":null, "ConsumedQuantity":1.00}]');
var1.forEach(function (e) {
Object.keys(e).forEach(function (key) {
if (e[key] == id) {
//doing some stuff here
}
});
});
This code works perfectly when the value in the JSON doesn't contain double quotes. This JSON is produced from a list of Model in MVC.
I use #Html.Raw(Json.Encode(ViewBag.materialDetails)) to convert the list to JSON. When there is a double quote, then it doesn't enter into the forEach.
Any help is appreciated :)
#Html.Raw(Json.Encode(ViewBag.materialDetails)) should return valid JSON data so you don't need to add ticks around it or JSON.parse it.
If you change
var var1 = JSON.parse('#Html.Raw(Json.Encode(ViewBag.materialDetails))');
to:
var var1 = #Html.Raw(Json.Encode(ViewBag.materialDetails));
it might work
In viewmodel object, below is the property:
public IList<CollegeInformationDTO> CollegeInformationlist { get; set; }
In VIEW, javascript is as follow:
var obj = JSON.stringify('#Model.CollegeInformationlist');
alert(obj[1].State); //NOT WORKING, giving string char
$.each('#Model.CollegeInformationlist', function (i, item) {
var obj = JSON.stringify(item);
var r = $.parseJSON(obj);
alert(r.State); //just giving undefined.
});
Please guide here, how i can get JSON object in javascript.
You could use the following:
var json = #Html.Raw(Json.Encode(#Model.CollegeInformationlist));
This would output the following (without seeing your model I've only included one field):
<script>
var json = [{"State":"a state"}];
</script>
Working Fiddle
AspNetCore
AspNetCore uses Json.Serialize intead of Json.Encode
var json = #Html.Raw(Json.Serialize(#Model.CollegeInformationlist));
MVC 5/6
You can use Newtonsoft for this:
#Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model,
Newtonsoft.Json.Formatting.Indented))
This gives you more control of the json formatting i.e. indenting as above, camelcasing etc.
In ASP.NET Core the IJsonHelper.Serialize() returns IHtmlContent so you don't need to wrap it with a call to Html.Raw().
It should be as simple as:
<script>
var json = #Json.Serialize(Model.CollegeInformationlist);
</script>
After use codevar json = #Html.Raw(Json.Encode(#Model.CollegeInformationlist));
You need use JSON.parse(JSON.stringify(json));
Pass the object from controller to view, convert it to markup without encoding, and parse it to json.
#model IEnumerable<CollegeInformationDTO>
#section Scripts{
<script>
var jsArray = JSON.parse('#Html.Raw(Json.Encode(#Model))');
</script>
}
If You want make json object from yor model do like this :
foreach (var item in Persons)
{
var jsonObj=["FirstName":"#item.FirstName"]
}
Or Use Json.Net to make json from your model :
string json = JsonConvert.SerializeObject(person);
The following code worked for me
var chartD = JSON.parse(JSON.stringify([#Json.Serialize(#Model)]));
I'm creating a json in javascript in that way
jsonArr.push({
position: 'WN',
wind: windWN,
wave: waveWN,
sea: seaWN
});
var myJsonString = JSON.stringify(jsonArr);
I'm sending it via an AJAX method with jsonData: jsonData:Ext.encode(myJsonString)
My json array looks like that when I send it :
In PHP side, I'm getting the Json and decoding it that way :
$rawpostdata = file_get_contents("php://input");
$rawpostdata2 = json_decode($rawpostdata, true);
I tried print_r( $rawpostdata2[1]); and got '{', as the second character of the "string", and I can't understand why.
In the other side, I tried print_r($rawpostdata), cut/past the result in a $string and retest my json_decode like that :
$rawpostdata = file_get_contents("php://input");
// print_r($rawpostdata);
$string = '[{"position":"N","wind":"2","wave":"65","sea":"65"},{"position":"E","wind":"3","wave":"5","sea":"6"},{"position":"S","wind":"56","wave":"4","sea":"8"},{"position":"W","wind":"1","wave":"56","sea":"84"},{"position":"NE","wind":"5","wave":"6","sea":"65"},{"position":"ES","wind":"6","wave":"45","sea":"6"},{"position":"SW","wind":"69","wave":"8","sea":"4"},{"position":"WN","wind":"7","wave":"8","sea":"56"}]';
$rawpostdata2 = json_decode($string,true);
print_r ($rawpostdata2[1]);
It gives me the correct result !
Array (
[position] => E
[wind] => 3
[wave] => 5
[sea] => 6 )
Do you have some explanations?
EDIT : I make it working by making another json_decode
$rawpostdata = file_get_contents("php://input");
$rawpostdata2 = json_decode($rawpostdata,true);
$rawpostdata3 = json_decode($rawpostdata2,true);
But I don't really understand...
First, you create json string:
var myJsonString = JSON.stringify(jsonArr);
Then you encode the resulting string into json again:
Ext.encode(myJsonString)
Thus, you have to json_decode() twice in PHP.
Try using $_POST instead of file_get_contets() which gives you a string.
you need to do a type cast on the result of json_decode like this:
<?php
$rawpostdata = file_get_contents("php://input");
$rawpostdata2 = (array) json_decode($rawpostdata,true);
?>
I hope this works for you.. Cheers..!!