0

I'm turning a string into an object, then looping over that object. For some reason, if the string is semi-correctly formatted and I don't do the first two steps (replacing the parentheses with curly brackets) it works fine.

However, the replacement puts single ' instead of " (although it still parses without error). The parse misses putting the second id underneath the employeeType, and mistakenly puts it under employee.

https://codepen.io/MrMooCats/pen/zwpQGa

var str = "(id,created,employee(id,firstname,employeeType(id),lastname),location)";

str = str.replace(/[(]/g, "{"); // Possible problem line?
str = str.replace(/[)]/g, "}"); // Possible problem line?
str = str.replace(/([A-z])\s*{/g, "$1\":{");
str = str.replace(/([A-z])\s*([},])/g, "$1\":null$2");
str = str.replace(/({)/g, "{\"");
str = str.replace(/(,)/g, ",\"");
var objectStr = JSON.parse(str); // Object created, but wrong


var objectOutput = function(obj, counter) {
    for(var i in obj) {
      console.log(Array(counter+1).join("-") + " " + i);
        if(obj.hasOwnProperty(i)){
          if (obj[i] != null) {
            objectOutput(obj[i], counter+1);
          } else {
            counter = 0;
          }
        }
    }
};

objectOutput(objectStr, 0);

Actual output:

" id"

" created"

" employee"

"- id"

" firstname"

" employeeType"

"- id"

" lastname"

" location"

Expected Output

" id"

" created"

" employee"

"- id"

"- firstname"

"- lastname"

"- employeeType"

"-- id"

" location"
8
  • I guess my first question would be, how is your string supposed to be formatted? And why are you using a string to create an object? Commented May 9, 2017 at 15:27
  • // Works fine if the ( are { instead and remove the first two lines - that's unreadable, can you just show what works? Commented May 9, 2017 at 15:27
  • I added a codepen, it has all the code exactly as here and the output Commented May 9, 2017 at 15:28
  • That codepen isn't very useful. How is your string actually going to be formatted? Do you have an example? Why do you use a string? Where is it coming from? @Organiccat Commented May 9, 2017 at 15:31
  • ...the replacement puts single ' instead of "... I don't know what that means. There are no single quotes in the replaced string. ...The parse misses putting the second id underneath the employeeType, and mistakenly puts it under employee... Don't know what you mean there either. The second id is under employee. Commented May 9, 2017 at 15:40

1 Answer 1

1

To get desired output you need to fix your objectOutput functrion:

    // Works fine if the ( are { instead and remove the first two lines
    var str = "(id,created,employee(id,firstname,employeeType(id),lastname),location)";

    str = str.replace(/[(]/g, "{"); // Possible problem line?
    str = str.replace(/[)]/g, "}"); // Possible problem line?
    str = str.replace(/([A-z])\s*{/g, "$1\":{");
    str = str.replace(/([A-z])\s*([},])/g, "$1\":null$2");
    str = str.replace(/({)/g, "{\"");
    str = str.replace(/(,)/g, ",\"");
    var objectStr = JSON.parse(str); // Object created, but wrong


    var objectOutput = function(obj, counter) {
        for (var i in obj) {
            console.log(Array(counter + 1).join("-") + " " + i);
            if (obj.hasOwnProperty(i)) {
                if (obj[i] != null) {
                    objectOutput(obj[i], counter + 1);
                }
            }
        }
    };
    objectOutput(objectStr, 0);

I would also change regex this way:

    var str = "(id,created,employee(id,firstname,employeeType(id),lastname),location)";

    str = str.replace(/\(/g, "{").replace(/\)/g, "}");
    str = str.replace(/([_a-zA-Z][_a-zA-Z0-9]*)\s*([,{}])/g, function(m, name, x){
        return '"'+name+'":' + (x != '{' ? 'null' : '') + x;});
    var objectStr = JSON.parse(str);

    var objectOutput = function(obj, counter) {
        for (var i in obj) {
            console.log(Array(counter + 1).join("-") + " " + i);
            if (obj.hasOwnProperty(i)) {
                if (obj[i] != null) {
                    objectOutput(obj[i], counter + 1);
                }
            }
        }
    };
    objectOutput(objectStr, 0);

Sign up to request clarification or add additional context in comments.

2 Comments

Ah, so the screw up wasn't in the regex conversion it was resetting the counter. I just realized I misread my object, the codepen console wasn't showing the second id (for performance reasons? no idea). And the single tics are still odd (If you throw a console.log(str) right before the JSON.parse), but it all works out. Thanks!
@Organiccat Yes, your regex kind of worked ok, as long as input strings do not contain unexpected characters. Check alternative regex in my answer that does the same.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.