Retrieving Values of Json Data Inside JSON Array in Mysql - mysql

I have JSON column, containing the JSON array. My Scenario, is to get all the the records where value of url is
'"example.com/user1"' is present. I have trouble writing the query for this operation.
Record1
[
{
"id": "1",
"firstname": "user1",
"url": "example.com/user1"
},
{
"id": "2",
"firstname": "user2",
"url": "example.com/user2"
}
]
Record2
[
{
"id": "1",
"firstname": "user3",
"url": "example.com/user3"
},
{
"id": "2",
"firstname": "user2",
"url": "example.com/user2"
}
]
......
......
......
Record10
[
{
"id": "1",
"firstname": "user10",
"url": "example.com/user10"
},
{
"id": "2",
"firstname": "user1",
"url": "example.com/user1"
}
]
The Query Which I ran is:
Select internal_id from users_dummy where JSON_EXTRACT(user_friends, '$[0].url') = "example.com/user1" or JSON_EXTRACT(user_friends, '$[1].url') = "example.com/user1";
So o/p was:
Record1, Record10
Is this the proper way to search for the values across the records?
Thanks in advance.

You can use JSON_SEARCH like this:
SELECT *
FROM users_dummy
WHERE JSON_SEARCH(user_friends, 'one', 'example.com/user1', NULL, '$[*].url') IS NOT NULL
demo on dbfiddle.uk
You can use the following solution in case you are using objects instead of arrays:
SELECT *
FROM users_dummy
WHERE JSON_SEARCH(user_friends, 'one', 'example.com/user1', NULL, '$.*.url') IS NOT NULL
demo on dbfiddle.uk

Related

Add a new element/field to every JSON array/record in an existing JSON file - python 3

I have JSON files that consists of 10+ records, like the one below.
Example:
[
{
"ID": null,
"entity": "xxx",
"Name": "Abc",
},
{
"ID": null,
"entity": "yyy",
"Name": "efg",
}
]
I want to add a new element "Date": "xx/xx/xx" to every record, like this:
[
{
"ID": null,
"entity": "xxx",
"Name": "Abc",
"Date": "xx/xx/xx"
},
{
"ID": null,
"entity": "yyy",
"Name": "efg",
"Date": "xx/xx/xx"
}
]
The order does not matter.
So far I have something like this:
date = 'xx-xx-xx'
def file(data, json):
with pathlib.Path(json).open('r+') as upfile:
fdata = json.load(upfile)
fdata.append(data)
upfile.seek(0)
json.dump(fdata, updfile)
...
new_ele = {'Date: ': date}
file(new_ele, file.json)
But my result is like this:
[
{
"ID": null,
"entity": "xxx",
"Name": "Abc",
},
{
"ID": null,
"entity": "yyy",
"Name": "efg",
},
{
"Date": "xx-xx-xx"
}
]
How can I get the Date into every single record?
Thank you
Once imported, your json is a list of dictionaries. So go through all list elements (which are dictionaries) and update them with the update method:
def update_json(data, json_path):
with pathlib.Path(json_path).open('r+') as upfile:
fdata = json.load(upfile)
for elt in fdata:
elt.update(data)
upfile.seek(0)
json.dump(fdata, upfile)

extract values from JSON using jq

I have a JSON object that looks like this:
{
"Accounts": [
{
"Id": "1",
"Name": "Joe",
"Zip": "11111"
},
{
"Id": "2",
"Name": "Jack",
"Zip": "22222"
}
]
}
I am trying to write a jq query that gives me this:
[
{
"Id": "1",
"Name": "Joe"
},
{
"Id": "2",
"Name": "Jack"
}
]
How can I do that? Thanks.
jq '.Accounts | map({ Id, Name })'
Will produce
[
{
"Id": "1",
"Name": "Joe"
},
{
"Id": "2",
"Name": "Jack"
}
]
as you can try online using this demo.
.Accounts selects the Accounts key
map() will apply the following for each object [docs]
Create object with Id and Name key [docs]
Demo https://jqplay.org/s/v01P2gDVc8
You can do
[.Accounts[] | {Id, Name}]

convert JSON from one key value pair to another

I want to generate new JSON from the existing, but I am not able to do so.
Given JSON:
[
{
"id": "1",
"firstName": "john",
"lastName": "doe"
},
{
"id": "2",
"firstName": "michal",
"lastName": "foo"
},
{
"id": "3",
"firstName": "john",
"lastName": "smith"
}
]
want to convert it to:
[
{
"id": "1",
"firstName": "john-doe"
},
{
"id": "2",
"firstName": "michal"
},
{
"id": "3",
"name": "john-smith"
}
]
I want only id name, but want lastName when only the firstName is same.
So, I am not able to do this condition of merging name, and add surname only when firstName is same
Please try to mention the following in your question:
Technologies you are using
What you are trying to do/build
Code you have already tried to write
Errors (if any)

lodash sort an array of objects by a property which has an array of objects

I have a an object. I am able to sort the items by using lodash's _.orderBy().
However, in one of the scenario I have to sort by subject, which is an array of objects. Items inside the subject array are already sorted based on the name.
As subject is an array of the objects, I need to consider the first item for sorting.
[
{
"id": "1",
"name": "peter",
"subject": [
{
"id": "1",
"name": "maths"
},
{
"id": "2",
"name": "social"
}
]
},
{
"id": "2",
"name": "david",
"subject": [
{
"id": "2",
"name": "physics"
},
{
"id": "3",
"name": "science"
}
]
},
{
"id": "3",
"name": "Justin",
"subject": [
]
}
]
You can use _.get() to extract the name (or id) of the 1st item in subjects. If no item exists, _.get() will return undefined, which can be replaced with a default value. In this case, we don't want to use an empty string as a default value, since the order would change. Instead I'm checking if the value is a string, if it is I use lower case on it, if not I return it as is.
const arr = [{"id":"1","name":"peter","subject":[{"id":"1","name":"maths"},{"id":"2","name":"social"}]},{"id":"2","name":"david","subject":[{"id":"2","name":"physics"},{"id":"3","name":"science"}]},{"id":"3","name":"Justin","subject":[]}]
const result = _.orderBy(arr, o => {
const name = _.get(o, 'subject[0].name')
return _.isString(name) ? name.toLowerCase() : name
})
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
Use _.sortBy with a comparison/sorting function argument. Your function itself can look into the receiving arguments subject key (I think its the subject you want to compare?)
Since you have the question also tagged with ES6 here is an JS only solution via Array.sort:
let arr = [ { "id": "1", "name": "peter", "subject": [ { "id": "1", "name": "maths" }, { "id": "2", "name": "social" } ] }, { "id": "2", "name": "david", "subject": [ { "id": "2", "name": "physics" }, { "id": "3", "name": "science" } ] }, { "id": "3", "name": "Justin", "subject": [] }, ]
const result = arr.sort((a,b) =>
a.subject.length && b.subject.length
? a.subject[0].name.localeCompare(b.subject[0].name)
: a.subject.length ? -1 : 1)
console.log(result)

insert the array into the database

I am getting this result when I am using graph api . it is in array format
{
"id": "216805086",
"name": "raj sharma",
"first_name": "raj ",
"last_name": "sharma",
"link": "https://www.facebook.com/raj.sharma.5",
"username": "raj .sharma.5",
"favorite_teams": [
{
"id": "198358615428",
"name": "Mumbai Indians"
},
{
"id": "190313434323691",
"name": "Indian Cricket Team"
}
],
"favorite_athletes": [
{
"id": "100787839962234",
"name": "Saina Nehwal"
}
],
"gender": "male",
"email": "raj.discoverme#gmail.com",
"timezone": 5.5,
"locale": "en_GB",
"verified": true,
"updated_time": "2013-08-13T06:01:17+0000"
}
I am working in a php language and phpmyadmin database . Now i want to insert the array into my database . Should i make a column for id , name , first_name ,last_name,link,favorite_teams etc or should i make a one column for all of this ........
how toinsert tha array into the database
Actually this is not an array. This is JSON. In JSON there are two formats,
JSONArray [ ]
JSONObject { }
You are getting the JSONObject as your output. There is a function in PHP callerd JSONDecode.
Go through this you will get idea.
Storing facebook app data in a database is against Facebook policy http://developers.facebook.com/policy/
$data = '{
"id": "216805086",
"name": "raj sharma",
"first_name": "raj ",
"last_name": "sharma",
"link": "https://www.facebook.com/raj.sharma.5",
"username": "raj .sharma.5",
"favorite_teams": [
{
"id": "198358615428",
"name": "Mumbai Indians"
},
{
"id": "190313434323691",
"name": "Indian Cricket Team"
}
],
"favorite_athletes": [
{
"id": "100787839962234",
"name": "Saina Nehwal"
}
],
"gender": "male",
"email": "raj.discoverme#gmail.com",
"timezone": 5.5,
"locale": "en_GB",
"verified": true,
"updated_time": "2013-08-13T06:01:17+0000"
}';
//decode to get as php variable
$values = json_decode($data,true); //true to decode as a array not an object
$sql = "INSERT INTO TableName (id,name,first_name,last_name,link,username)
VALUES ('".$values['id']."','".$values['name']."','".$values['first_name']."','".$values['last_name']."','".$values['link']."','".$values['username']."')";
mysql_query($sql);
Json_decode() takes a JSON encoded string and converts it into a PHP variable.