0

I have the following HTML tags generated by back end

<select name="brand" class="form-control">
    <option value="1" data-info="[{id=1, name=detail#1}, {id=2, name=detail#2}, {id=3, name=detail#3}]">brand#1</option>
    <option value="2" data-info="[{id=3, name=detail#3}, {id=4, name=detail#4}, {id=5, name=detail#5}]">brand#2</option>
</select>

I am trying to access data-info value when user change option, so i try this code

$('#brand').on('change', function(){
    var optionSelected = $("option:selected", this);
    var info = optionSelected.data("info")

    console.log(typeof info)
})

But when i get typeof info i get a string, and i need and object.

If i try JSON.parse(info) i get SyntaxError: JSON.parse: expected property name or '}' at line 1 column 3 of the JSON data

I understand this error could be for two reasons info is already parsed or it is not valid json.

Any help is appreciated

1
  • The JSON that you have is invalid Commented Apr 7, 2016 at 18:06

1 Answer 1

3

jQuery's JSON handler only translates valid JSON. The JSON you have in there is not valid. Specifically, it's missing the necessary quotes and you're using = rather than :. It should read something like:

<option value="1" data-info='[{"id":1, "name":"detail#1"}, {"id":2, "name":"detail#2"}, {"id":3, "name":"detail#3"}]'>brand#1</option>

For reference, the JSON spec.

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

1 Comment

you are right @Ouroborus, i just fixed the error in backend, now is rendering valid json as you suggest and i am getting objects

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.