Home » Javascript » Rails ActiveRecord to_json leaving invalid json characters

Rails ActiveRecord to_json leaving invalid json characters

Posted by: admin November 1, 2017 Leave a comment

Questions:

I am trying to convert a rails ActiveRecord to json and keep getting invalid characters when I try to parse the data.

@appts = current_cbu.appointments.on_date(@date).as_json.to_json

I have overridden the ‘as_json method as follows:

  def as_json
    hash = {}
    hash["title"] = calendar_title
    hash["start"] = start_at.strftime("%Y-%m-%d")
    hash["end"] = end_at.strftime("%Y-%m-%d")
    hash["url"] = "/admin/appointments/#{id}"
    hash["base_amount"] = base_amount
    hash["upcharge_amount"] = upcharge_amount
    hash["upcharge_reason"] = upcharge_reason
    hash["total_with_tip_amount"] = total_with_tip_amount
    hash["customer_notes"] = customer_notes
    hash
  end

Then in my view I post this to a separate application, but on the separate application i get errors when I try to do JSON.parse(). How can I convert @appts to valid json without having to do a .gsub for every character that is invalid?

 var post_data = {
    'type': 'initial',
    'appts': '#{@appts}',
    'assignments': '#{@daily_assignments_json}',
    'events': '#{@events_json}',
    'date' : '#{@date}'
  }
  targetWindow.postMessage(JSON.stringify(post_data), '#{@scheduler_location}');

Error: VM30212:1 Uncaught SyntaxError: Unexpected token
in JSON at position 663

Answers: