MySQL getting JSON value - mysql

In my MySql players table I have a column called achievements and it is a text field which in this particular row has this value:
[
{
"value":11,
"globalID":23000000
},
{
"value":11,
"globalID":23000001
},
{
"value":11,
"globalID":23000002
},
...
{
"value":6044730,
"globalID":23000065
}
]
Near the bottom of the array you can see this object:
{
"value":48,
"globalID":23000062
},
I need to be able to parse the value field and show it as a warhero field. But how can I do this? The globalID will stay the same but the value changes. And because the globalID is after the value value I can't use what was used in this post: https://stackoverflow.com/a/21596032/4942382
What SQL query would I need to run to get that value?
Thanks!

The design of a table does not even meet the first normalisation level if it stores a non-atomic value in a single column, which is the case with this type of JSON encoded values.
Now if you have no access to the JSON functions available to MySql version 5.7+, and your globalID has a fixed number of digits, then you could do some string matching as follows.
For example, if you need the value that goes with globalID 23000062, then you could do this:
SELECT players.*,
CAST(
SUBSTRING_INDEX(
SUBSTRING_INDEX(achievements, '"globalID":23000062', 1),
'"value":',
-1
)
AS UNSIGNED) AS json_extracted_value
FROM players
WHERE INSTR(achievements, '"globalID":23000062') > 0
But really, you should seriously consider redesigning your database.

You should have never saved the JSON in your table, you already broke the rules of relational database design.
mysql cannot make sense of the data, so no SQL query will help you, you have 2 options:
Fix your database design, create tables to hold that data instead of JSON
Fetch the data, decode the JSON, and do all type of manipulations and hacks to get your desired value.

Related

Sum value from multiple JSON data in postgress sql

I have datatype JSON stored on postgress db, e g. column:jsondata.
Each row on db table represent one JSON data of the same format,e.q.
{
"ID": "001",
"Name": "Britney",
"DebtAmount": "100.23"
}
There are multiple records with the above data with different ID.
How do I do JSON query to get the total sum of Debt Amount accross multiple records?
Thanks alot for your help.
If there is already existing solution, please point me to it.
You can use json_each_text() function in order to extract key-value pairs from the JSON object after fixing the current value in order to get a valid JSON value, and apply a SUM() aggregation through filtering out the key names DebtAmount along with applying float convertion for the values such as
SELECT SUM(value::float)
FROM t,
LATERAL json_each_text(js)
WHERE key = 'DebtAmount'
Demo

How to Take Just Data Without Column Names in NodeJS with MySql

When I want to take data from mysql in NodeJS, it results like
RowDataPacket { name : 'John', marks : 56}
But I want to take this data without column names or other things. I need to use just NodeJS for this problem. I saw some JSON solutions but I can’t do this cause of my program.
The result of a 'SELECT' query will be an array of objects. And each object defines a row.
You can either iterate through the array and use the key to access its value like results.forEach( row => { row[key] })
or if your result returns a single row, then you can access the object as results[0].
You need to set an index and then obtain the value.
For example if you are storing your response in a variable called results.
Use the following:
x = results[0].name;
Then you can use this variable/name further in your program.

How to extract values from a numeric-keyed nested JSON field in MySQL

I have a MySQL table with a JSON column called sent. The entries in the column have information like below:
{
"data": {
"12":"1920293"
}
}
I'm trying to use the mysql query:
select sent->"$.data.12" from mytable
but I get an exception:
Invalid JSON path expression. The error is around character position 9.
Any idea How I can extract the information? The query works fine for non-numeric subfields.
#Ibrahim,
You have an error in your code. If you use number (or spaced words) as key in a JSON data type in MySQL, you'll need to double-quote it.
Therefore, the correct MySQL statement in your case is:
select sent->'$.data."12"' FROM mytable;
Thanks,
#JeffreyKilelo

solr update with json causes 'error parsing json field. unexpected object_start'

I downloaded solr 4.6.1 and I am attempting to update the solr index using the following via command line:
curl http://localhost:8983/solr/update?commit=true -H 'Content-type:application/json' -d '
[{
"id" : "1",
"phoneNumber_ss": [{"foo_ss" : "bar"}]
}]
'
I am using the example schema.xml, which is why i used all the "_ss" fields.
The issue is that when I execute this I get the following response:
{"responseHeader":{"status":400,"QTime":1},"error":{"msg":"Error parsing JSON field value. Unexpected OBJECT_START","code":400}}
This seems to be related to the value specified for phoneNumber_ss field which is an array of objects. If I make the value into an array or an object it works fine, its only when it is an array of objects that the issue occurs.
Any help is much appreciated.
I don't think Solr support storing objects into a multivalued field. You can store it as a array of string. You might also store the object as a string and parse it in your application.
If you have such use case that you want to have all the objects from Solr only, you can follow the steps..
Create a multivalued field for your keys.
Maintain the same order of keys and create another multivalued field for values.
So, you can get the keys and values in same order in different fields. But in this approach you might face problems while updating those multivalued fields. You might want to look here
And finally, you are also missing some syntax in your update statement.
set – set or replace a particular value, or remove the value if null is specified as the new value
add – adds an additional value to a list
Check http://wiki.apache.org/solr/UpdateJSON

MySQL increment value in a text field

Say I have a text field with JSON data like this:
{
"id": {
"name": "value",
"votes": 0
}
}
Is there a way to write a query which would find id and then would increment votes value?
I know i could just retrieve the JSON data update what I need and reinsert updated version, but i wonder is there a way to do this without running two queries?
UPDATE `sometable`
SET `somefield` = JSON_REPLACE(`somefield`, '$.id.votes', JSON_EXTRACT(`somefield` , '$.id.votes')+1)
WHERE ...
Edit
As of MySQL 5.7.8, MySQL supports a native JSON data type that enables efficient access to data in JSON documents.
JSON_EXTRACT will allow you to access a particular JSON element in a JSON field, while JSON_REPLACE will allow you to update it.
To specify the JSON element you wish to access, use a string with the format
'$.[top element].[sub element].[...]'
So in your case, to access id.votes, use the string '$.id.votes'.
The SQL code above demonstrates putting all this together to increment the value of a JSON field by 1.
I think for a task like this you're stuck using a plain old SELECT followed by an UPDATE (after you parse the JSON, increment the value you want, and then serialize the JSON back).
You should wrap these operations in a single transaction, and if you're using InnoDB then you might also consider using SELECT ... FOR UPDATE : http://dev.mysql.com/doc/refman/5.0/en/innodb-locking-reads.html
This is sort of a tangent, but I thought I'd also mention that this is the type of operation that a NoSQL database like MongoDB is quite good at.