Problem with Metafield value type JSON

Hello,

I need to figure out one issue with the metafield which has value type = ‘json’.

metafield = ShopifyAPI::Metafield.new
metafield.variant_id = custom_bundle.master_variant_id
metafield.namespace = ‘custom_bundle’
metafield.key = ‘product_data’
metafield.value = child_products_data.to_json
metafield.type = ‘json’
metafield.save!

When child_products_data is empty then metafield.value set the value as .

instead of in the metafield, how can I set it completely blank.

like:

From API call I can not sent nil value for metafield.value if child_products_data is empty, because it gives error like #<ShopifyAPI::Errors::HttpResponseError: {"errors":{"value":["can’t be blank."]}.

Have any solution for this??

Hey @Av18

I looked into how the native admin handles this, and it appears metafields are simply deleted when their value is removed.

E.g. With bundle value:

With blank bundle value:

Hey @SBD

You are correct. Metafields are simply deleted when their value is removed. However, this only works for metafields that do not have a JSON type. For JSON type metafields, updating a nil value is prevented.

For example

when I update metafield.value

metafield.value = child_products_data.to_json
metafield.type = ‘json’
metafield.save!

to this metafield.value = nil
then it prevent like {"value":["can’t be blank."]}.

Hey @Av18

Thanks for the response. I just tried with a JSON field and saw the same results.

E.g. Here’s a json field

Which the API returns as:

But setting it to blank in admin (or running metafieldDelete / REST delete) clears the value:

I.e. try .delete instead of .save of a nil value.

Let me know if I’m not following :slightly_smiling_face:

Hey @SBD

“Thank you for providing the correct solution.”

It successfully clears the values when I delete the metafield.