How to MongoDBimport json tree not as one document? - php

I've got a this json file to import:
{"Spele": {
"Laiks": "2017/01/11",
"Skatitaji": 6740,
"Vieta": "Newlands Stadium",
"T": [
{
"Uzvards": "Antamo",
"Vards": "Dennis"
},
{
"Uzvards": "Prompa",
"Vards": "Pedro"
}
],
"Komanda": [
{
"Nosaukums": "Barcelona",
"Speletaji": {"Speletajs": [
{
"Loma": "V",
"Nr": 16,
"Uzvards": "Sam",
"Vards": "Sidney"
},
{
"Loma": "A",
"Nr": 17,
"Uzvards": "Cisovsky",
"Vards": "Marian"
}
}
]
}
But unfortunately, mongoDBimport imports it as one document. Are there any tips on how to manage trees? I can work with mongo.exe or PHP.
maybe manually adding:
"_id" : { "$oid" : "50906d7fa3c412bb040eb577" }
Would solve it?

i have been working with a similar project some times ago and i parse those as php variables and than store them in database using sql query
first decode json using the follow code:
$response is your json file
$data = json_decode($response);
than you can use this to take data and store to a variable
$newvat = $data->myjson->prices;

Related

Printing a nested JSON Array value [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 3 months ago.
I've been trying to find ways to print the individual data but can't seem to figured out where I'm going wrong.
I started with this but I get no results. Before this I tried nesting loops but also got nowhere either.
$data = curl_exec($ch);
$d = json_decode($data, true);
foreach($d as $k=>$v){
echo $v['value']['displayName'];
}
Then I tried the following with only got me some of the results. I'm not sure where I'm going wrong with this.
foreach(json_decode($data,true) as $d){
foreach($d as $k=>$v){
foreach($v as $kk=>$vv){
echo $kk.$vv;
}
}
}
The JSON looks like the following:
{
"value": [
{
"id": "",
"name": "",
"etag": "",
"type": "Microsoft.SecurityInsights/alertRules",
"kind": "Scheduled",
"properties": {
"incidentConfiguration": {
"createIncident": true,
"groupingConfiguration": {
"enabled": false,
"reopenClosedIncident": false,
"lookbackDuration": "PT5M",
"matchingMethod": "AllEntities",
"groupByEntities": [],
"groupByAlertDetails": null,
"groupByCustomDetails": null
}
},
"entityMappings": [
{
"entityType": "Account",
"fieldMappings": [
{
"identifier": "FullName",
"columnName": "AccountCustomEntity"
}
]
},
{
"entityType": "IP",
"fieldMappings": [
{
"identifier": "Address",
"columnName": "IPCustomEntity"
}
]
}
],
"queryFrequency": "P1D",
"queryPeriod": "P1D",
"triggerOperator": "GreaterThan",
"triggerThreshold": 0,
"severity": "Medium",
"query": "",
"suppressionDuration": "PT1H",
"suppressionEnabled": false,
"tactics": [
"Reconnaissance",
"Discovery"
],
"displayName": "MFA disabled for a user",
"enabled": true,
"description": "Multi-Factor Authentication (MFA) helps prevent credential compromise. This alert identifies when an attempt has been made to diable MFA for a user ",
"alertRuleTemplateName": null,
"lastModifiedUtc": "2022-11-14T02:20:28.8027697Z"
}
},
...
...
...
Here is how you can get the display name without a loop. Notice that the 0 is the key value of the array since it doesn't have a name.
We start from the value, and we move one layer deeper by selecting the first array 0. Now we need to select the properties and finally, we can get the displayName from there.
$displayName = $d["value"][0]["properties"]["displayName"];
echo($displayName);
/*
Here is a quick demonstration:
value:
{
0:
{
...
properties:
{
...
displayName: [We made it!]
}
}
}
*/
And here is a very good post that explains this in more detail
How to decode multi-layers nested JSON String and display in PHP?

Looping through a json file to find a particular value in PHP

My json file look likes
myjson.json
[
{"name":"category_01","data":
[
{"id":"1","word":"ma","given_value":"1"},
{"id":"3","word":"me","given_value":"1"},
] }
[
{"name":"category_02","data":
[
{"id":"1","word":"vea","given_value":"1"},
{"id":"3","word":"ve","given_value":"1"},
] }
So what I want here is, check whether a particular value is in this json array using php. Assume that,
myphp.php
$word = 've';
if this value is in the above array, should find is it in category_01 or category_02. and also want to find given_value of matching word.
I just tried in this way,
$data = file_get_contents ("myjson.json");
$json = json_decode($data, true);
foreach($arr as $item) {
$uses = ($item['word']= $word);
}
This doesn't work. How can I fix this, Please help me!
First of all, the JSON you posted is invalid. I think it should look like this:
[
{
"name": "category_01",
"data": [{
"id": "1",
"word": "ma",
"given_value": "1"
},
{
"id": "3",
"word": "me",
"given_value": "1"
}
]
},
{
"name": "category_02",
"data": [{
"id": "1",
"word": "vea",
"given_value": "1"
},
{
"id": "3",
"word": "ve",
"given_value": "1"
}
]
}
]
Try using on online tool like https://jsonlint.com/ to check your JSON. (if you get errors i recommend build the json again from scratch).
I also recommend checking your json before using it:
if ($arr === null && json_last_error() !== JSON_ERROR_NONE) {
die("incorrect json data");
}
To get your value you have to KNOW how your data looks like and then process it:
foreach($arr as $category) {
foreach($category['data'] as $data) {
if(strstr($data['word'], $word))
echo $category['name'].' '.$data['word'].' '.$data['given_value']."\n";
}
}

trying to decode json file to variable but its only returning null

I'm trying to decode a json file to a PHP variable, but the PHP variable is just null. This is my PHP:
$champions['names'] = json_decode(file_get_contents("file://D:/Xampp/htdocs/lol-champions.json"),true);
echo $champions['names']['champions'][1]['name'];
This is my json file:
"champions":[
{
"id" : 103,
"name" : "Ahri",
},
{
"id" : 84,
"name" : "Akali",
}]
As #Paul Crovella stated, here is the correct version :
{
"champions": [{
"id": 103,
"name": "Ahri"
}, {
"id": 84,
"name": "Akali"
}]
}
Also if you want to call it;
echo $champions->champions[1]->name;

Elasticsearch find documents by location

I have indexed a number of documents in my Elasticsearch database and when I query for all them I see they have a structure like this:
GET http://localhost:9200/restaurants/restaurant/_search
Output:
{
"took": 4,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 362,
"max_score": 1,
"hits": [
{
"_index": "restaurants",
"_type": "restaurant",
"_id": "2",
"_score": 1,
"_source": {
"businessName": "VeeTooNdoor Dine",
"geoDescription": "Right next to you2",
"tags": {},
"location": {
"lat": -33.8917007446,
"lon": 151.1369934082
}
}
},
...
]
}
}
I now want to search for restaurants around a given geo-location and following the documentation [1] I use something like this:
{
"filtered" : {
"query" : {
"match_all" : {}
},
"filter" : {
"geo_distance" : {
"distance" : "1km",
"location" : {
"lat": -33.8917007446,
"lon": 151.1369934082
}
}
}
}
}
The thing I have changed is the match_all since I don't want to specify any search field in particular, I only care about the geo location.
When I run the query I get the following message:
"error": "SearchPhaseExecutionException[Failed to execute phase [query], all shards failed; shardFailures {[olAoWBSJSF2XfTnzEhKIYA][btq][3]: SearchParseException[[btq][3]: from[-1],size[-1]: Parse Failure [Failed to parse source [{\n \"filtered\" : {\n \"query\" : {\n \"match_all\" : {}\n },\n \"filter\" : {\n .....
Now I did notice the following on the tutorial page:
Update: The automatic mapping of “geo enabled” properties has been
disabled since publishing this article. You have to provide the
correct mapping for geo properties. Please see the documentation.
Which gives me the impression that I have to create a "mapping" which specifies the field types. However, in the document it refers to doesn't give me enough information on how to actually do this. It shows blobs of JSON but I'm not sure about the correct URL's for this.
Further more, I'm using the PHP client and I'm not sure if it even supports mappings as is demonstrated in this walk through [2].
I somehow get the impression that quite a bit of changes have been made to the query DSL etc. and that a lot of examples on the web don't work anymore, I could be wrong through. I'm using Elasticsearch 1.0.0.
[1] http://www.elasticsearch.org/blog/geo-location-and-search
[2] http://blog.qbox.io/elasticsearch-aggregations
Things that might be wrong:
1: your query shows pin.location and your field is just location.
2: your _mapping for location could be wrong
Does your mapping show something like:
"location": {
"type": "geo_point",
"geohash_precision": 4
}
I was able to run this search against some of my own data:
POST /myindex/mydata/_search
{
"query": {
"match_all": {}
},
"filter": {
"geo_distance" : {
"distance" : "100km",
"_latlng_geo" : {
"lat": -33.8917007446,
"lon": 151.1369934082
}
}
}
}
... a snippet of my mapping:
"properties": { .....
"_latlng_geo": {
"type": "geo_point",
"geohash_precision": 4
}
.....
EDIT : How to use Put Mapping API
You can create the mapping when you create the index like so:
PUT /twitter/
{
"settings" : {
"number_of_shards" : 1
},
"mappings" : {
"tweet":{
"properties":{
"latlng" : {
"type" : "geo_point"
}
}
}
}
}
removing the query is what finally worked for me:
{
"filter": {
"geo_distance" : {
"distance" : "300km",
"location" : {
"lat" : 45,
"lon" : -122
}
}
}
}
You have to replace "location" by "restaurant.location" because ElasticSearch interprete it like a type not like a attribute.
{
"filtered" : {
"query" : {
"match_all" : {}
},
"filter" : {
"geo_distance" : {
"distance" : "1km",
"restaurant.location" : {
"lat": -33.8917007446,
"lon": 151.1369934082
}
}
}
}
I hope it helps you.
As stated in the docs:
"We use the generic PHP stdClass object to represent an empty object. The JSON will now encode correctly."
http://www.elasticsearch.org/guide/en/elasticsearch/client/php-api/current/_dealing_with_json_arrays_and_objects_in_php.html
In your case you should use
$searchParams['body']['query']['filtered']['query']['match_all'] = new \stdClass();

Parsing Complex JSON with PHP

I am new to PHP and not very clear how to parse JSON with PHP. This is the JSON i am getting from a third party
{ "data":
{ "current_condition":
[
{"cloudcover": "0", "humidity": "13", "observation_time": "05:47 AM", "precipMM": "0.0",
"pressure": "1016", "temp_C": "20", "temp_F": "69",
"visibility": "10", "weatherCode": "113",
"weatherDesc": [ {"value": "Sunny" } ],
"weatherIconUrl": [ {"value": "http:\/\/www.worldweatheronline.com\/images\/wsymbols01_png_64\/wsymbol_0001_sunny.png" } ],
" winddir16Point": "SW", "winddirDegree": "218", "windspeedKmph": "12", "windspeedMiles": "7"
}
],
"request": [
{"query": "Lat 32.12 and Lon 76.53", "type": "LatLon" }
],
"weather": [
{
"date": "2012-11-04", "precipMM": "0.0", "tempMaxC": "20", "tempMaxF": "69", "tempMinC": "1", "tempMinF": "34",
"weatherCode": "113", "weatherDesc": [ {"value": "Sunny" } ],
"weatherIconUrl": [ {"value": "http:\/\/www.worldweatheronline.com\/images\/wsymbols01_png_64\/wsymbol_0001_sunny.png" } ],
"winddir16Point": "SW", "winddirDegree": "218", "winddirection": "SW", "windspeedKmph": "12", "windspeedMiles": "8"
},
{
"date": "2012-11-05", "precipMM": "0.0", "tempMaxC": "20", "tempMaxF": "67", "tempMinC": "4", "tempMinF": "39",
"weatherCode": "113", "weatherDesc": [ {"value": "Sunny" } ],
"weatherIconUrl": [ {"value": "http:\/\/www.worldweatheronline.com\/images\/wsymbols01_png_64\/wsymbol_0001_sunny.png" } ],
"winddir16Point": "SSW", "winddirDegree": "210", "winddirection": "SSW", "windspeedKmph": "12", "windspeedMiles": "7"
}
]
}
}
I am getting this weather information as JSON data which includes following information
Current information
Weather information for next 2 days
I do not want all information but only specific one like
current_condition
temp_C
temp_F
weatherDesc
Than i want some data from the weather information provides for next 2 days
date
tempMaxC
tempMinC
weatherIconUrl
windspeedKmph
i tried this code in PHP
$jsonIterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator(json_decode($weather, TRUE)),
RecursiveIteratorIterator::SELF_FIRST);
which seems to give me the JSON decoded data in the array format but i got confused in how to fetch those specific values from the PHP data. I can iterate over the Data
foreach ($jsonIterator as $key => $value) {
if(is_array($value)) {
foreach ($value as $key => $value) {
}
} else {
// echo "$key\n";
}
but not sure how to fetch values as described above.Any help or pointer for resources will really be helpful
Why don't you just use json_decode and then process the resulting object?
Example: http://codepad.org/ciw3ogAu
I used ob_get_content() because I don't want to mess up with the escape sequences, but the focus is on this line:
$result = json_decode($my_json_string);
It's not difficult to obtain information. For example if you want the current temperature in Celsius:
echo $result->data->current_condition[0]->temp_C;
You can get an array of the future two days (http://codepad.org/bhOcd3eT):
$weatherarray = $result->data->weather; // An array with two elements
You use $result->xxx instead of $result["xxx"] because json_decode will create objects for objects. You can change it to be arrays by calling json_decode($my_json_string, true), then you access members using the following way:
echo $result["data"]["current_condition"][0]["temp_C"];
You need to decode your json object, but you don't need to iterate it. Just access the information you want :
$decoded = json_decode($weather);
$date = $data->current_condition->data->weather->date;
$tempMaxC = $data->current_condition->data->weather->tempMaxC;
$tempMinC = $data->current_condition->data->weather->tempMinC;
$weatherUrl = $data->current_condition->data->weather->weatherIconUrl;
$windspeedKmph = $data->current_condition->data->weather->windspeedKmph;
I would go with this approach to access your data :
$data = json_decode($weather);
And then your can easily get what you want this way :
print_r($data->data->current_condition);
or in a loop...
$decode=json_decode($file);
echo $decode->data->current_condition[0]->temp_C;
echo $decode->data->current_condition[0]->temp_F;
echo $decode->data->current_condition[0]->weatherDesc[0]->value;
foreach ($decode->data->weather as $data) {
echo $data->date;
echo $data->tempMaxC;
echo $data->tempMinC;
echo $data->weatherIconUrl;
echo $data->windspeedKmph;
}

Categories