Проблем с импорт на данни в json файл



Направих една форма, в която въвеждам разни неща. Свързах я с Backend Services. Всичко работи коректно. След филтрация връща обекта, който ми е нужен. Но проблемът е, че не мога да го добавя в моя json файл, който захранва приложението с данни.

Направих го по този начин:

$('#add').on('click', function () {
var title = $('#title').val();
var price = $('#price').val();
var country = $('#country').val();
var year = $('#year').val();
var genre = $('#genre').val();
var duration = $('#duration').val();
var summary= $('#summary').val();
var rating = $('#rating').val();

var el = new Everlive('iCUPUElKASGpeqyh');
var productsData = el.data('Products');
var product = {
'Title': title,
'Price': price,
'Specs': {'Country': country, 'Year': year, 'Genre': genre, 'Duration': duration},
'Summary': summary,
'Rating': rating
.then(function (data) {
var id = data.result.Id;
var query = new Everlive.Query();
query.where().eq('Id', id).done().select('Title', 'Price', 'Specs', 'Summary', 'Rating');
.then(function (products) {
var newMovie = products.result[0];
$.getJSON('products.json', function (data) {
var db = JSON.parse(data);

.then(function () {

Идеята е с натискане на един бутон да пратя инфото от формата към базата. След това да ми филтрира резултата ида ми го прати като обект. До тук добре. Но после искам и да вкара този обект в локален json. Той е масив от обекти.

Но с push не става.



Като направих това, което ми каза, сега се мъчи да парсне json-a, но ми дава грешка:

SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data

Това е файла:

[ { "id": 1, "title": "The Ring", "price": 3, "specs": { "country": "USA", "year": 2002, "genre": "Horror", "duration": 115 }, "summary": "A journalist must investigate a mysterious videotape which seems to cause the death of anyone in a week of viewing it.", "rating": 4, "image": { "small": "assets/images/the-ring-small.jpg", "large": "assets/images/the-ring-large.jpg" } }, { "id": 2, "title": "Star Wars: Episode I - The Phantom Menace", "price": 4, "specs": { "country": "USA", "year": 1999, "genre": "Adventure", "duration": 136 }, "summary": "Two Jedi Knights escape a hostile blockade to find allies and come across a young boy who may bring balance to the Force, but the long dormant Sith resurface to reclaim their old glory.", "rating": 5, "image": { "small": "assets/images/star-wars-phantom-menace-small.jpg", "large": "assets/images/star-wars-phantom-menace-large.jpg" } }, { "id": 3, "title": "Hackers", "price": 2, "specs": { "country": "USA", "year": 1995, "genre": "Crime", "duration": 107 }, "summary": "A young boy is arrested by the U.S. Secret Service for writing a computer virus and is banned from using a computer until his 18th birthday. Years later, he and his new-found friends discover a plot to unleash a dangerous computer virus, but they must use their computer skills to find the evidence while being pursued by the Secret Service and the evil computer genius behind the virus.", "rating": 3, "image": { "small": "assets/images/hackers-small.jpg", "large": "assets/images/hackers-large.jpg" } }, { "id": 4, "title": "Fast & Furious", "price": 3, "specs": { "country": "USA", "year": 2001, "genre": "Action", "duration": 106 }, "summary": "Los Angeles police officer Brian O'Connor must decide where his loyalties really lie when he becomes enamored with the street racing world he has been sent undercover to destroy.", "rating": 5, "image": { "small": "assets/images/fast-and-furious-small.jpg", "large": "assets/images/fast-and-furious-large.jpg" } }, { "id": 5, "title": "The Dictator", "price": 5, "specs": { "country": "USA", "year": 2012, "genre": "Comedy", "duration": 85 }, "summary": "The heroic story of a dictator who risks his life to ensure that democracy would never come to the country he so lovingly oppressed.", "rating": 5, "image": { "small": "assets/images/the-dictator-small.jpg", "large": "assets/images/the-dictator-large.jpg" } }, { "id": 6, "title": "Terminator", "price": 7, "specs": { "country": "USA", "year": 1984, "genre": "Action", "duration": 110 }, "summary": "A human-looking indestructible cyborg is sent from 2029 to 1984 to assassinate a waitress, whose unborn son will lead humanity in a war against the machines, while a soldier from that war is sent to protect her at all costs.", "rating": 5, "image": { "small": "assets/images/terminator-small.jpg", "large": "assets/images/terminator-large.jpg" } }, { "id": 7, "title": "Jurassic Park", "price": 6, "specs": { "country": "USA", "year": 1993, "genre": "Sci-Fi", "duration": 127 }, "summary": "During a preview tour, a theme park suffers a major power breakdown that allows its cloned dinosaur exhibits to run amok.", "rating": 2, "image": { "small": "assets/images/jurassic-park-small.jpg", "large": "assets/images/jurassic-park-large.jpg" } }, { "id": 8, "title": "South Park: Bigger, Longer and Uncut", "price": 8, "specs": { "country": "USA", "year": 1999, "genre": "Animation", "duration": 81 }, "summary": "Follows the misadventures of four irreverent grade-schoolers in the quiet, dysfunctional town of South Park, Colorado.", "rating": 5, "image": { "small": "assets/images/south-park-small.jpg", "large": "assets/images/south-park-large.jpg" } }, { "id": 9, "title": "Shoker", "price": 4, "specs": { "country": "USA", "year": 1989, "genre": "Horror", "duration": 109 }, "summary": "After being sent to the electric chair, a serial killer uses electricity to come back from the dead and carry out his vengeance on the football player who turned him in to the police.", "rating": 5, "image": { "small": "assets/images/shocker-poster-small.jpg", "large": "assets/images/shocker-large.jpg" } } ]

от zdzdz (222 точки)


Съжелявам, че те подведох колега, getJSON си връща обект (явно автоматично си го парсва). Проблема е, че няма как да си запазиш данните, освен ако не ползваш localStorage или sessionStorage. Нещо подобно:

$.getJSON('products.json', function (data) { var updatedProducts = data.push(newMovie); sessionStorage.setItem('products', JSON.stringify(updatedProducts)); });

от NEw358 (209 точки)