Error: JSON.parse: expected ',' or ']' after array element - ajax

Am newbie to Json am getting this error while call json my json file expected ',' or ']'
[
{
"modules":
[
{
"title":"name of module1",
"description":"description of module1",
"weeks":[{"id":1, "title":"Week 01"}]
},
{
"title":"name of module2",
"description":"description of module2",
"weeks":[{"id":2, "title":"Week 02"},{"id":3,"title":"Week 03"}]
}
]
},
{
"products":
[
{
"url":"http://dummyimage.com/242x200/f3f3f3/2d2d2d.png",
"description":"Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec id elit non mi porta gravida at eget metus. Nullam id dolor id nibh ultricies vehicula ut id elit.",
"viewurl" : "/",
"savebtn" : "save"
},
{
"url":"http://dummyimage.com/242x200/f3f3f3/2d2d2d.png",
"description":"Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec id elit non mi porta gravida at eget metus. Nullam id dolor id nibh ultricies vehicula ut id elit.",
"viewurl" : "/",
"savebtn" : "save"
}
]
}
]
hope i did correct i dont know what is happening its getting Error: JSON.parse: expected ',' or ']' after array element am attempting to use in angular js controller
app.controller('settingsController', function($scope, $http){
$http.get('assets/javascripts/datas.json').then(function(result){
$scope.employe = result.data;
$scope.prod = result
})
});
and in view
<div class="col-sm-6 col-md-4" ng-repeat="datas in prod.products">
<div class="thumbnail">
<img ng-src="{{ datas.url }}" alt="product">
<div class="caption">
<h3>{{ datas.caption}} </h3>
<p>{{ datas.description}}</p>
<p><a role="button" class="btn btn-primary" ng-href="{{datas.viewurl}}">Button</a> <a role="button" class="btn btn-default" href="#">{{datas.savebtn}}</a></p>
</div>
</div>
</div>
and the error in console
Error: JSON.parse: expected ',' or ']' after array element at line 76 column 9 of the JSON data cc#/test/assets/javascripts/vendors/angular.js:14:289 Ud/this.defaults.transformResponse<#/test/assets/javascripts/vendors/angular.js:69:58 xc/<#/test/assets/javascripts/vendors/angular.js:68:352 r#/test/assets/javascripts/vendors/angular.js:7:288 xc#/test/assets/javascripts/vendors/angular.js:68:336 b#/test/assets/javascripts/vendors/angular.js:70:65 ye/e/l.promise.then/K#/test/assets/javascripts/vendors/angular.js:100:59 ye/f/<.then/<#/test/assets/javascripts/vendors/angular.js:101:235 Zd/this.$get

This error occurred for me when I parsed JSON from a string literal. When I copied in the JSON, I forgot that the escape sequences would need to be double escaped.
Example of the problem:
var data = JSON.parse('[{"key": "This value has \"a quoted\" string"}]');
While the string value is valid JSON, the escape sequences are lost. Then need to be double escaped:
Corrected version:
var data = JSON.parse('[{"key": "This value has \\\"a quoted\\\" string"}]');

Well for me the problem occurs if I have a :// (e.g. http://) inside my json stirng for this reason I replaced it and it worked.

Related

Trying to get property 'id' of non-object in laravel session foreach

Im practicing laravel and right now Im in the session topic
this is my controller
public function set(Request $request){
$product = Product::findOrFail($request->input('id'));
session()->put('product', $product);
return redirect()->route('cart');
}
when i tried to echo the{{session()->get('product')}} on my blade it produce an output of
{
"id":9,
"name":"Lorem ipsum dolor sit amet",
"description":"Proin pretium, mauris id convallis tempus, lorem enim tincidunt nulla, vel pharetra sapien odio eget ligula. Sed maximus, massa sit amet condimentum bibendum, nisi ante vestibulum ipsum, ut ornare justo lorem mollis justo.",
"price":"22.21",
"cover_image":"JRwg9TSKTvUTvuij.jpg",
"created_at":"2018-07-20 03:47:57",
"updated_at":"2018-07-20 03:47:57"
}
but when i tried to use foreach on it by using
#foreach(session()->get('product') as $key)
{{$key->id}}
#endforeach
it shows an error of Trying to get property 'id' of non-object
can someone guide me why I'm I getting this error thanks.
You are iterating through your single object but what you seem to need to do is:
{{ session()->get('product')->id }}
If you want to loop then you can do:
#foreach (session()->get('product')->toArray() as $key => $value)
{{ $key }}: {{ $value }}
#endforeach
This will result in:
id: 9
name: Lorem ipsum dolor sit amet
description: Proin pretium, mauris id convallis tempus, lorem enim tincidunt nulla, vel pharetra sapien odio eget ligula. Sed maximus, massa sit amet condimentum bibendum, nisi ante vestibulum ipsum, ut ornare justo lorem mollis justo.
price: 22.21
cover_image: JRwg9TSKTvUTvuij.jpg
created_at: 2018-07-20 03:47:57
updated_at: 2018-07-20 03:47:57
However, just as a sidenote this is bad practice because your coupling your view with a session entry. Ideally your view would just take a product object as a view parameters and use that directly. That way you can pass it that object either from the session or from a database query.
If you are trying to get single value from an object you can get like this.
{{ session()->get('product')->id }}
Or If you wish to print all data, First you have to convert object into an array then use foreach.
#foreach (session()->get('product')->toArray() as $key => $value)
{{ $key }}: {{ $value }} </br>
#endforeach
Try it this way :
#foreach(session()->get('product') as $key)
{{$key['id']}}
#endforeach
You are trying to iterate an object. When you try to do this you get the public properties from the object. In your example $key is one of those properties, not the model itself.
When you echo {{ }} a Model __toString gets called which returns the serialized model as json.
If you want that model's id you can just grab it like normal. session('product')->id
If you want you can serialize the Model to an array:
foreach ($model->toArray() as $key => $value) {
...
}

elasticsearch - can mix number and number array datatype in same index same type?

I created 2 documents of autogenerated test data in an index/type using:
POST /mymixedata/lists-and-nums/
{
"pat_first_name": "Balduin",
"pat_last_name": "Goodbairn",
"gender": "Male",
"diag_codes": "T84028D",
"prov_first_name": "Dwight",
"prov_last_name": "Croutear",
"prov_addr": "617 Monterey Drive",
"rand_list": [
123,
456,
123
],
"notes": "Quisque porta volutpat erat. Quisque erat eros, viverra eget, congue eget, semper rutrum, nulla. Nunc purus."
}
POST mymixedata/lists-and-nums
{
"pat_first_name": "Goorbi",
"pat_last_name": "Goorbson",
"gender": "Female",
"diag_codes": "S22039D",
"prov_first_name": "Tarrah",
"prov_last_name": "Jimeno",
"prov_addr": "13483 Walton Road",
"rand_list": 100,
"notes": "Phasellus sit amet erat. Nulla tempus. Vivamus in felis eu sapien cursus vestibulum.\n\nProin eu mi. Nulla ac enim. In tempor, turpis nec euismod scelerisque, quam turpis adipiscing lorem, vitae mattis nibh ligula nec sem.\n\nDuis aliquam convallis nunc. Proin at turpis a pede posuere nonummy. Integer non velit.\n\nDonec diam neque, vestibulum eget, vulputate ut, ultrices vel, augue. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec pharetra, magna vestibulum aliquet ultrices, erat tortor sollicitudin mi, sit amet lobortis sapien sapien non mi. Integer ac neque.\n\nDuis bibendum. Morbi non quam nec dui luctus rutrum. Nulla tellus.\n\nIn sagittis dui vel nisl. Duis ac nibh. Fusce lacus purus, aliquet at, feugiat non, pretium quis, lectus."
}
Notice that for the field rand_list, one doc has an array of nums and the other has a single num. Querying the index/type like so:
{
"query": {
"bool": {
"must": [
{
"range": {
"rand_list": {
"gt": "50"
}
}
}
]
}
}
}
I get back both of the documents, which seems like the behavior that I want (assuming its checking the array of nums in the fist doc and the single num in the second to determine if they contain a value > 50).
Other than here, I can't find much documentation on how elastic treats fields that sometimes have arrays and sometimes have single values.
Can anyone explain what's going on? Do single values count as arrays even when they don't have surrounding brackets (ie. is field: 123 same as field: [123] in a doc)?
Thanks :)
Guess I just did not read the docs close enough. Turns out that yes, can have either arrays or single values of same datatype for the same fields in documents.

How can I integrate fitVids.js into a .load function?

I'm new to jquery and I need to integrate a bit of code and I'm calling it from an external html file with the .load() function. That part of code it's a .div containing a video and a description. All I need to do is to make fitVids work on the code loaded from the external file.
This is the html loaded in the div.featured-container:
<div class="featured-container">
<div class="container player clearfix">
<div class="span8 video-container">
<iframe width="600" height="338" src="http://www.youtube.com/embed/QkhqI49QeaM?rel=0" frameborder="0" allowfullscreen></iframe>
</div>
<div class="span4 featured-content">
<div class="feat-meta">May 8, 2010 at 16:50 / by Silviu Stefu</div>
<h2>Retiner - Mobile UI Kit</h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse.
</p>
<a class="button-normal" href="">Read More...</a>
</div>
</div>
</div>
And here is the JS:
//load the first list item link
var firstLoad = $('.thumbnails li:nth-child(2) a').attr('href')+' .player';
$('.featured-container').load(firstLoad,'',showTheContent());
function showTheContent() {
$('.player').fitVids().fadeIn('slow');
}
//load the links on click
$('.thumbnails li a').click(function(){
var toLoad = $(this).attr('href')+' .player';
$('.player').fadeOut('slow',loadContent);
$('#load').remove();
$('#load').fadeIn('normal');
function loadContent() {
$('.featured-container').load(toLoad,'',showNewContent());
}
function showNewContent() {
$('.player').fadeIn('slow',hideLoader());
}
function hideLoader() {
$('#load').fadeOut('normal');
}
return false;
});
So, where I should put the .fitVids() function to make the fideo fluid?
I would use the success function for this, so that if its loaded run the code.
$("#success").load("file.html", function(response, status, xhr) {
if (status == "succes") {
// your code
}
});

How do I disable the close button in my goog.ui.Dialog?

I would like to get rid of the close/X button on the top right corner of my Google Closure dialog.
I am browsing the documentation (http://closure-library.googlecode.com/svn-history/r8/trunk/closure/goog/docs/class_goog_ui_Dialog.html) and cannot find the method to do so.
The method is there! See http://closure-library.googlecode.com/svn/docs/class_goog_ui_Dialog.html
dialog.setHasTitleCloseButton(false);
Regards,
Rene
The goog.ui.Dialog title-bar close button can be disabled by first calling goog.ui.Dialog.prototype.getTitleCloseElement() followed by goog.style.showElement(el, display).
Example
var dialog = new goog.ui.Dialog();
dialog.setContent('Lorem ipsum dolor sit amet, consectetuer' +
'adipiscing elit. Aenean sollicitudin ultrices urna. Proin vehicula ' +
'mauris ac est. Ut scelerisque, risus ut facilisis dictum, est massa ' +
'lacinia lorem, in fermentum purus ligula quis nunc. Duis porttitor ' +
'euismod risus. Nam hendrerit lacus vehicula augue. Duis ante.');
dialog.setTitle('Lorem ipsum');
dialog.setButtonSet(goog.ui.Dialog.ButtonSet.createYesNo());
var titleCloseEl = dialog.getTitleCloseElement();
goog.style.showElement(titleCloseEl, false);

wordpress get_posts() returns empty the_ID()

I've got a problem with loading a list of posts in a certain category via AJAX. the funny part is, that I get a right amount of posts, I get the excerpts right for each post, but ID, and title are empty, plus the date is wrong (1.1.1970). this is my function within functions.php:
function ajax_cat(){
if( isset($_GET['action'])&& $_GET['action'] == 'ajax_cat'){
$my_id = htmlspecialchars($_GET["id"]);
$args = array(
'offset' => 0,
'category' => $my_id,
'orderby' => 'post_date',
'order' => 'DESC',
'post_type' => 'post',
'post_status' => 'publish' );
$myposts = get_posts( $args );
foreach( $myposts as $post ) : setup_postdata($post); ?>
<div class="nadpis1" id="<?php the_ID(); ?>" >
<?php the_title(); ?>
<span class="sipka"><?php the_date("d.m. Y"); ?></span>
</div>
<div class="vnutro" ><?php echo the_excerpt();?></div>
<?php endforeach;
die();
}
}
originally this code was inside the loop and worked well. this is what i get now:
<div class="nadpis1" id="" >
<span class="sipka">01.01. 1970</span>
</div>
<div class="vnutro" ><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p></div>
<div class="nadpis1" id="" >
<span class="sipka"></span>
</div>
<div class="vnutro" ><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec adipiscing ultrices posuere. Aenean et egestas enim. Phasellus sit amet nisl elit. Sed pulvinar, purus nec commodo condimentum, lectus risus lacinia urna, sed ultrices magna est vitae turpis. Sed convallis pulvinar gravida. Sed non sem sem, at lobortis tellus. Etiam commodo risus vitae diam cursus volutpat. [...]</p></div>
<div class="nadpis1" id="" >
<span class="sipka"></span>
</div>
<div class="vnutro" ><p>gfdgdfsgngfjty ty jghj ty jtyhjghj dh gfdj5 fgjfdthbkdfgxhjsrgv ,f xfhbtyj dc rtjdtxhvcntydxvhctr shxfc</p></div>
<div class="nadpis1" id="" >
<span class="sipka">01.01. 1970</span>
</div>
<div class="vnutro" ><p>Vitajte vo WordPress. Toto je váš prvý článok. Môžete ho upraviť alebo vymazať a potom už len začať písať!</p></div
>
thanks for any suggestions!
You can't use the_ functions outside of The Loop. Try using get_the_title($postid); and similar get_ functions. Note that the get_ functions don't display the value, they return it, so you'll have to use echo get_the_title($postid);.
Edit: Nevermind, I see that you're using setup_postdata(). However, it could still be worthwhile to use the functions which pass in the ID instead of the ones that change global settings. Try inspecting $post with print_r to see which data you already have in your foreach loop without calling a whole bunch of other database queries.

Resources