1

I have a JSON object that I want users to edit.

When I print it plainly, like {{json}} I get the string, {"car":{"color":"blue"}}. But when I print it in any sort of editable field, like

<input v-model="json">

I get this:

enter image description here

Things I've tried:

  • html:v-model / html:value - Empty input
  • <textarea v-model="json">{{json}}</textarea> - I get [object Object], BUT when I inspect the element, I see the JSON printed like a string - which is what I want!

How do I get v-model to print JSON as a string in an input?

0

1 Answer 1

1

You can always use JSON.stringify(someObject) to get the stringified version of an object, however you cannot bind this via v-model.

If I understand you correctly, you do actually want the user to edit the stringified json and not provide input fields for the object properties? (The latter would be a much cleaner solution and could easily be achieved with a v-for="(value, key) in object" though)

But if that's the case, you also have to consider what to do when the user enters invalid json.

My approach to this would be to use a stringified version of the object to bind to the textarea v-model and watch it to determine on any change if it is a valid and parsable json format.

Working example here: https://codesandbox.io/s/ol9nn9j566
It'd probably need some debouncing, and better error handling but it should get you started.

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

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.