Zach
Zach

Reputation: 1185

MySQL Replace Syntax -- wrap specific piece of text

Within a table, there is a params row that has some JSON encoded data -- as such:

{"categories":211,"singleCatOrdering":"","menu-anchor_title":"","menu-anchor_css":"","menu_image":"","menu_text":1,"page_title":"","show_page_heading":0,"page_heading":"","pageclass_sfx":"","menu-meta_description":"","menu-meta_keywords":"","robots":"","secure":0}

What I need to do is wrap [] around the categories parameter - to look as such:

{"categories":[211],"singleCatOrdering":"","menu-anchor_title":"","menu-anchor_css":"","menu_image":"","menu_text":1,"page_title":"","show_page_heading":0,"page_heading":"","pageclass_sfx":"","menu-meta_description":"","menu-meta_keywords":"","robots":"","secure":0}

I have tried the following (and a bunch of other failed ones) with no-dice:

UPDATE j17_menu SET params = REPLACE(params,'"categories":%,','"categories":[%],') WHERE component_id = 10021;

Am I possibly using the wildcard option wrong? Any nudges in the right direction would be a huge help. Thanks!

Upvotes: 0

Views: 134

Answers (1)

Eugen Rieck
Eugen Rieck

Reputation: 65304

This one will work independent of the context

UPDATE j17_menu 
SET params=CONCAT (
    SUBSTR(params,1,LOCATE('"categories":',params)),
    '"categories":[',
    substr(
        params,
        LOCATE('"categories":',params)+13,
        LOCATE(',',params,LOCATE('"categories":',params))-LOCATE('"categories":',params)-13
    ),
    ']',
    substr(params,LOCATE(',',params,LOCATE('"categories":',params)))
)
WHERE component_id = 10021;

Upvotes: 1

Related Questions