I need to convert a string to a JSON object that gets returned from a Learning Management System. Once the string is a JSON Object I’m going to use it as part of a jQuery plugin I am writing. Here is what I have so far:
callback to convert: (I do not have access to the server-side code (it resides on an LMS (AICC), I just access it via javascript and the callback is below, so I am stuck with this text. I do believe after each line there is \n, but this is the exact format I receive …. nothing but text.)
ERROR=0
ERROR_TEXT=Successful
VERSION=2.2
AICC_DATA=[CORE]
STUDENT_ID=01234567
STUDENT_NAME=Doe, John R
SCORE=83
TIME=02:35:37
CREDIT=C
LESSON_LOCATION=page_1
LESSON_STATUS=INCOMPLETE
[Core_Lesson]
[Objectives_Status]
The is what I am looking to convert it to:
{'ERROR':'0','ERROR_TEXT':'Successful','VERSION':'2.2','AICC_DATA':'[CORE]','STUDENT_ID':'01234567','STUDENT_NAME':'Doe, John R','SCORE':'83','TIME':'02:35:37','CREDIT':'C','LESSON_LOCATION':'page_1','LESSON_STATUS':'INCOMPLETE'}
Here is the jQuery I am using: (as you can see I am trying to do this without a loop if possible 🙂
$.get(_url,{command:"GetParam",version:"2.2",session_id:_sid},function(response)
{
/* this is my attempt at using a RegExp */
var match = RegExp('[?&]' + urlVar + '=([^&]*)').exec(response);
/* I thought maybe I could do it using an eval(), but I get an error -> Expected "]" */
var t = eval('{['+response+']}');
});
I am confident that I could figure this out using a loop, but I really would like to get this working without the for loop. Is this even possibible? Thanks!
If your lines do end in “\n” then you could try this:
If your names can contain “=” of course that’d be a problem.
What that does is match the basic format of your name/value lines (NAME=VALUE) and builds an object. The JavaScript
.replace()method for strings calls that function repeatedly for each successive match, with the parameters being the entire match (which here we don’t care about), and then each matched group (things in parens in the regex).