2

I'm trying to create a JSON tree out of an each loop, that get information from several id's on the page. Consider that each id has names like "textHolder1, textHolder2" etc.

$('[id^="textHolder"]').each(function(){
TextElementID = this.id;
TextElementContent = $(this).text();
TextElementClass = $(this).attr('class');
TextElementStyle = $(this).attr('style');

json =  JSON.stringify({textElements:{TextElementID:{textContent:TextElementContent,textClass:TextElementClass, textStyle: TextElementStyle}}}, null, 4);
});

alert(json)

And I'm trying to get this output in JSON:

{
"textElements": {
    "textHolder1": {
        "textContent": "The content",
        "textClass": "theclass",
        "textStyle": "some-styles"
    }
   "textHolder2": {
        "textContent": "The content1",
        "textClass": "theclass2",
        "textStyle": "some-styles2"
    }
}
}

How is this done, and what am I doing wrong?

2 Answers 2

4

You need to build up an object and then JSON.stringify the final object.

var t = {};
$('[id^="textHolder"]').each(function(){
    var $this = $(this);
    t[this.id] = {
        textContent: $this.text(),
        textClass: $this.attr('class'),
        textStyle: $this.attr('style')
    };
});

json = JSON.stringify({textElements: t });
Sign up to request clarification or add additional context in comments.

1 Comment

@Kim, If it works for you, you can mark it as answer of the question.
0

If it is required to use a variable value as key in JSON, it is needed to be added into JSON with json[variable] instead of using it in {} like {variable:value}. Because {variable:value} is equals to {"variable":value} not {variableValue:value}.

So you need to define it like;

json={textElements:{}}
//TextElementID is your variable and it should be used as a key like that
json.textElements[TextElementID]={textContent:TextElementContent,textClass:TextElementClass, textStyle: TextElementStyle}

stringifiedJson =  JSON.stringify(json);

Comments

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.