1

I need to select a key from a json_encodED array from mysql..

SELECT * FROM json_field_table WHERE {var from JSON encoded array} = {expected value}

or something.. How I can do this?

PS.: Poor English, I know..

6
  • Regardless of your language knowledge, you should really, really take more time to make an actual question. It'S way too unspecific to answer it. Commented Jun 8, 2011 at 3:28
  • Well I think that's an answerable question. But only with: no. If you have a JSON encoded structure in your database table, you will first have to transfer it to the application to unpack and compare an entry of that array. MySQL provides no built-in functions to deal with JSON (it does for XML), and it's unlikely anyone has crafted a stored procedure for that yet. (Well, string searching is a workaround.) Commented Jun 8, 2011 at 3:31
  • @hakre sorry, Im Brasiliam and dont know how to create an question.. is complex to me. Commented Jun 8, 2011 at 3:40
  • @mario Select all from DB then decode json field, and check? Commented Jun 8, 2011 at 3:41
  • @Gabriel: Yes, that would be the *correct* approach. But that is obviously not a *workable* solution due to the overhead. Commented Jun 8, 2011 at 3:47

3 Answers 3

4

You'd have to use substring matching. MySQL doesn't have anything to deal with JSON data and treats it like it does any other piece of random text.

SELECT ... WHERE the_json_field LIKE '%"var":"value"%';
Sign up to request clarification or add additional context in comments.

Comments

0

Well, Gabriel, despite the nature of your question. I am supposing, your problem might be, you need to read a JSON value and based on that values, you need to retrieve the record set from the table. If this is the case, here is your solution.

// A sample json string
$json = '{ "field1": "value1", "field2": "value2" }'; 

// Here we will convert the json string into readable assocative array
$json_array = json_decode($json,true); 

//Next we will use it on a query
$query = "SELECT * json_field_table WHERE `".$json_array['field1']."` = 'Some Value' ";

//Execute the query
$result = mysql_query($query);

1 Comment

Can't you retrieve the row and then check it later on. What you are trying to do, will create a very inefficient solution. There might be better way to do, what you are trying to do. But, if you insist on going with your idea, then better go with @Marc B's solution.
0

with numbers (integers) you can filter out values, with alphanumeric strings is more complicated as the value stored is "jsonencoded"

check my answer to 17955206

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.