1

I am trying to create a valid JSON from my Wordpress custom fields. I am having issues here:

{"eu_price":"400", // this one is ok
 "other_prices":["{\"GBP\":\"330\",\"USD\":\"525\"}"] // this is not
}

How do I get rid of those slashes?

I am grabbing the data from a MySql database field, using this Wordpress function:

$my_product[other_prices] = get_post_meta( $product_id, '_regular_currency_prices', false );

Then I am using:

echo json_encode($my_product, JSON_UNESCAPED_SLASHES);

in order to return an encoded result.

In the database the field content is like:

{"GBP":"330","USD":"525"}

The full json response is:

{"user_country":"US","title":"Dress  1960","permalink":"http://site.dev/my_slug/","eu_price":"350","other_prices":["{\"GBP\":\"290\",\"USD\":\"460\"}"],"main_image":"http://doublej.dev/wp-content/uploads/2015/01/1100000003274_0-300x300.jpg"}

2 Answers 2

2

When you set $my_product['other_prices'] you are setting it as a string. If the database contains JSON, you'll need to decode it so that when when re-encode your response, it all makes sense.

$jsonEncodedData = get_post_meta( $product_id, '_regular_currency_prices', false );
$my_product['other_prices'] = json_decode($jsonEncodedData)
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for your answer, I already tried this, but as a result I get "null" instead. I wonder what I'm missing
well, then your data is probably invalid JSON - shouldn't be hard to diagnose that
I guess so, but I don't see why it doesn't work. If I try to hardcode $my_product[other_prices] = {"GBP":"330","USD":"525"} it works
From your post, it looks like get_post_meta returns an array containing a string - if that's the case you'll need something like json_decode($jsonEncodedData[0])
0

Dont manually build json string, use json_encode:

echo json_encode([
        'eu_price'=>'400',
        'other_prices'=>[
            'GBP'=>'330',
            'USD'=>'525'
        ]
    ]);

1 Comment

Well, Pauls answer is what i would suggest, if part of the data is already encoded.

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.