I have an imported CSV ($csv) with multiple headers, one of which is "Target Server". In the CSV this column has values device1, device2 etc.
I also have a hashtable ($hash) with name/value pairs of name(device1) - value(fqdn1) etc.
So I would like to replace the "device1" in CSV with the correct value from the hashtable, like:
foreach($row in $csv)
if($hash[$_.Name]){
$row."Target Server"= $hash[$_.Value]
}
Am I getting warm?
Use the ContainsKey() method to see if the hashtable contains an entry with a specific name/key:
foreach($row in $csv) {
if($hash.ContainsKey($row.'Target Server')) {
$row.'Target Server' = $hash[$row.'Target Server']
}
}
Related
I have a json file that maps alpha-2 codes to country names:
{
"AF": "Afghanistan",
"EG": "Ägypten",
...
}
I want to iterate over each key value pair to process the data. How would I be able to achieve that?
I tried the following but it always returns one big object that is not iterable in a key value manner:
$json = Get-Content -Path C:\countries.json | ConvertFrom-Json
I was able to achieve it like this:
foreach ($obj in $json.PSObject.Properties) {
$obj.Name
$obj.Value
}
I am trying to access the values of this array in PHP. It's a multidimensional array.
I need to get values from the array and insert it in the DB.
Inserting is the second part of the problem. First parts is getting the values from it.
JSON -
{
"itempicture":[
{
"status":"3"
},
{
"ItemCode":"001",
"ItemImage":"image1",
"ItemCategory":"shirt",
"ShowOnPOS":"Yes",
"LastModifiedOn":"2018-06-02 11:53:57"
},
{
"ItemCode":"002",
"ItemImage":"image2",
"ItemCategory":"shirt",
"ShowOnPOS":"Yes",
"LastModifiedOn":"2018-06-02 11:53:57"
}]}
Here the "itempicture" is the table name and all the keys, i.e 'itemcode', 'itemimage, etc are the SQL columns'".
I need to get the values of the SQL columns and insert it into the DB.
So far i have tried this -
$data = file_get_contents($url);
$json_array = (array)(json_decode($data));
print_r($json_array);
foreach($user->itempicture as $mydata)
{
echo $mydata->itempicture . "\n";
foreach($mydata->itempicture as $values)
{
echo $values->itempicture . "\n";
}
}
Using MYSQL in Object-oriented method to insert it in DB, with a simple query like "INSERT INTO table_name
VALUES (value1, value2, value3, ...)"
So table name will be the "itempicture" present in the array and values will be the values of the keys in the array.
This may be of help. Instead of looping through the properties with a foreach and printing, you'll want to use them to build an array to use as parameters for a prepared query, or build the query directly. But this shows you how to access those properties -
<?php
$j='{
"itempicture":[
{
"status":"3"
},
{
"ItemCode":"001",
"ItemImage":"image1",
"ItemCategory":"shirt",
"ShowOnPOS":"Yes",
"LastModifiedOn":"2018-06-02 11:53:57"
},
{
"ItemCode":"002",
"ItemImage":"image2",
"ItemCategory":"shirt",
"ShowOnPOS":"Yes",
"LastModifiedOn":"2018-06-02 11:53:57"
}]}';
$jo=json_decode($j);
print("status ".$jo->itempicture[0]->status."\n");
for($i=1;$i<count($jo->itempicture);$i++){
foreach($jo->itempicture[$i] as $prop=>$val){
print($prop." = ".$val."\n");
}
}
?>
There are some issues I have seen in your code:
You cast the result of json_decode($data) to an array, an then later you try to use property-access to access the "itempicture" property. I have removed this cast.
In the first foreach use the variable $user, I guess you meant to use $json_array.
The inner loop is not really used, you can access the properties directly
After having fixed this issues the code looks like that and works with your given JSON. I have just echo-ed the values since you have not told us which DB-abstraction you use, but you can use the values to populate the database.
$data = file_get_contents($url);
$json_array = (json_decode($data));
print_r($json_array);
foreach($json_array->itempicture as $mydata)
{
if (!property_exists($mydata, 'ItemCode')) {
// Ignore entries which are invalid (have no ItemCode property)
continue;
}
echo implode(' - ', [
$mydata->ItemCode,
$mydata->ItemImage,
$mydata->ItemCategory,
$mydata->ShowOnPOS,
$mydata->LastModifiedOn,
]), PHP_EOL;
}
I'm parsing a JSON string that is stored in a database.
{"name":"simon", "age":"23", "height":"tall"}
I'm pulling the data, then decoding. When running the code below, I'm receiving weird 'HASH' values back.
use JSON;
$data = decode_json($row->{'address'});
for my $key (keys %$data){
if($data->{$key} ne ''){
$XML .= " <$key>$data->{$key}</$key>";
}
}
// Returns data like so
<company_type>HASH(0x27dbac0)</company_type>
<county>HASH(0x27db7c0)</county>
<address1>HASH(0x27dba90)</address1>
<company_name>HASH(0x27db808)</company_name>
The Error happens when I have a data set like so:
{"name":"", "age":{}, "height":{}}
I don't understand why JSON / Arrays / Hashes have to be so difficult to work with in Perl. What point am I missing?
You are processing a flat hash, while your data in fact has another, nested, hashref. In the line
{ "name":"", "age":{}, "height":{} }
the {} may be intended to mean "nothing" but are in fact JSON "object", the next level of nested data (which are indeed empty). In Perl we get a hashref for it and that's what your code prints.
The other pillar of JSON is an "array" and in Perl we get an arrayref. And that's that -- decode_json gives us back the top-level hashref, which when dereferenced into a hash may contain further hash or array references as values. If you print the whole structure with Data::Dumper you'll see that.
To negotiate this we have to test each time for a reference. Since a dereferenced hash or array may contain yet further levels (more references), we need to use either a recursive routine (see this post for an example) or a module for complex data structures. But for the first level
for my $key (keys %$data)
{
next if $data->{$key} eq '';
my $ref_type = ref $data->{$key};
# if $data->{key} is not a reference ref() returns an empty string (false)
if (not $ref_type) {
$XML .= " <$key>$data->{$key}</$key>";
}
elsif ($ref_type eq 'HASH') {
# hashref, unpack and parse. it may contain references
say "$_ => $data->{$key}{$_}" for keys %{ $data->{$key} };
}
elsif ($ref_type eq 'ARRAY') {
# arrayref, unpack and parse. it may contain references
say "#{$data->{$key}}";
}
else { say "Reference is to type: $ref_type" }
}
If the argument of ref is not a reference (but a string or a number) ref returns an empty string, which evaluates as false, which is when you have plain data. Otherwise it returns the type the reference is to. Coming from JSON it can be either a HASH or an ARRAY. This is how nesting is accomplished.
In the shown example you are runnig into hashref. Since the ones you show are empty you can just discard them and the code for the specific example can reduce greatly, to one statement. However, I'd leave the other tests in place. This should also work as it stands with the posted example.
I'm trying to read a value from an object in a CSV File (Using PowerShell 3.0). Based on what that value is, I will create a new column and insert a value (in the same row).
For example, I have the CSV file:
Attribute1,Attribute2
Valuea1,Valueb1
Valueb1,Valuea1
Valuea1,Valueb1
Valueb2,Valuea2
Valuea2,Valueb2
For each "Valueb1" in Attribute2 insert a value "Found" into a new column Data. So in the end, it should look like this (notice just the added , if there is no "Found"):
Attribute1,Attribute2,Data
Valuea1,Valueb1,Found
Valueb1,Valuea1,
Valuea1,Valueb1,Found
Valueb2,Valuea2,
Valuea2,Valueb2,
I'm not familiar with how nested loops work with objects in CSV files using PowerShell.
Add a calculated property with a value depending on the value of Attribute2:
Import-Csv 'C:\input.csv' |
Select-Object -Property *,
#{n='Data';e={if ($_.Attribute2 -eq 'Valueb1') {'Found'} else {''}}} |
Export-Csv 'C:\output.csv' -NoType
I've tried this in powershell with -replace and with [RegEx]::replace. same issue. I want to use the value in a capture group to retrieve its value from a lookup duing the replace on a string.
assuming t is a a valid hash table of key/value where one key is 'gif'.
[RegEx]::Replace($_, "((/aaa)?/bbb[^']+).(jpg|png|bmp|gif)", "--`$1--`$2--`$3--$($t.Item('`$3'))++++`$1-UUUUU.`$3")
Needless to say, i've been unsuccessful with getting the hash lookup to work in this substitution.
If I understand correctly, you can use a MatchEvaluator like so:
$evaluator ={
$t = #{ "jpg"="This is a jpeg image";
"gif"="This is a gif image"}
$group1 = $args[0].groups[1]
$t["$group1"]
}
[RegEx]::Replace("test.gif","^.*\.(jpg|gif)", $evaluator,[Text.RegularExpressions.RegexOptions]::none)