sorry if this is a dumb question. My problem is I want make a PHP file that parses in JSON the contents of a MySQL table. The problem is i have a field that have JSON in it with breaklines:
{
"6cb20a9f-27fa-4d98-ac2e-e959eb3f0f63": {
"file": "",
"title": "",
"link": "",
"target": "0",
"rel": ""
},
"43aa1b15-986e-4303-afcf-628b835f10e5": {
"0": {
"value": "<p>This is an example description.<\/p>"
}
},
"97dacf42-398b-45c5-8536-baec4250b27e": {
"0": {
"value": "2012-10-19 00:00:00"
}
},
"20fec805-ebb1-4045-9f3d-ea90ad952e91": {
"0": {
"value": "A restaurant"
}
}
}
So at the moment of using the PHP it looks like this:
PHP Fail
What can I do for it to avoid the \n and \t, because I'm sending this parse to an iphone app and it doesn't recognize it. Thanks!
The PHP Code is something like this:
<?php>
$link = mysql_pconnect("localhost", "root", "") or die("Could not connect");
mysql_select_db("test") or die("Could not select database");
$arr = array();
$rs = mysql_query("SELECT * FROM people");
while($obj = mysql_fetch_object($rs)) {$arr[] = $obj;
}
echo '{"members":'.json_encode($arr).'}';
?>
Related
I use powershell and i want to put variable in json format into TMSL create role script. I want to put this variable into TablePermission parameter
json variable:
$filter=
[
{
"name": "DimGeography",
"filterExpression": "DimGeography[CountryRegionCode] = \"US\" "
}
]
TMSL script:
$Query='
{
"create": {
"parentObject": {
"database": "AW Internet Sales"
},
"role": {
"name": "test_filter",
"modelPermission": "read",
"tablePermissions": "'+$filter+'"
}
}
}'
This is script which I want to parametrize
{
"createOrReplace": {
"object": {
"database": "AW Internet Sales",
"role": "SalesManagerUS"
},
"role": {
"name": "SalesManagerUS",
"modelPermission": "read",
"tablePermissions": [
{
"name": "DimGeography",
"filterExpression": "DimGeography[CountryRegionCode] = \"US\" "
}
]
}
}
}
How can I put $filter to $Query to receive working script like above ?
You could try the below snippet :
$filter=
'[
{
"name": "DimGeography",
"filterExpression": "DimGeography[CountryRegionCode] = \"US\" "
}
]'
function populate-tsml ($filter)
{
$Query='
{
"create": {
"parentObject": {
"database": "AW Internet Sales"
},
"role": {
"name": "test_filter",
"modelPermission": "read",
"tablePermissions": '+$filter+'
}
}
}'
return $Query
}
$Query = populate-tsml -filter $filter
OUTPUT :
Thank you!
It wasn't necesseary to define a function, a little changes in quotation marks was enough.
Script below works:
$filter=
'[
{
"name": "DimGeography",
"filterExpression": "DimGeography[CountryRegionCode] = \"US\" "
}
]'
$Query='
{
"create": {
"parentObject": {
"database": "AW Internet Sales"
},
"role": {
"name": "test_filter",
"modelPermission": "read",
"tablePermissions": '+$filter+'
}
}
}'
I want to pass variables in for these values but I cant get them to go for example in user_id I want to pass the variable $userID
This is an example of the Body i'm using:
$body = '{
"data":
[
{
"user_id":$userID,
"type":"manual",
"date":"2021-01-30",
"duration":"150",
"jobcode_id":"15281216",
"notes":"This is a test of a manual time entry",
"customfields": {
"54138" : "IT Services",
"54136" : "Yes"
}
}
]
}'
I would use a double-quoted Here-String for that:
$userID = 'Alex'
$body = #"
{
"data": [{
"user_id": "$userID",
"type": "manual",
"date": "2021-01-30",
"duration": "150",
"jobcode_id": "15281216",
"notes": "This is a test of a manual time entry",
"customfields": {
"54138": "IT Services",
"54136": "Yes"
}
}]
}
"#
$body now contains:
{
"data": [{
"user_id": "Alex",
"type": "manual",
"date": "2021-01-30",
"duration": "150",
"jobcode_id": "15281216",
"notes": "This is a test of a manual time entry",
"customfields": {
"54138": "IT Services",
"54136": "Yes"
}
}]
}
The reason why $userID is not substituted for it's value in your example is because you are using a single quote (') character. PowerShell only substitutes when you use a double quote (") character.
This would give you the challenge that your data already contains double quotes. There Here string from Theo's answers works just fine but as a personal preference I would use a PowerShell hashtable to construct an object and convert it to Json using Convert-To-Json.
Example:
$userID = 'John'
$body = #{
"data" = ,#{
"user_id" = $userID;
"type" = "manual";
"date" = "2021-01-30";
"duration" = "150";
"jobcode_id" = "15281216";
"notes" = "This is a test of a manual time entry";
"customfield" = #{
"54138" = "IT Services";
"54136" = "Yes";
}
}
}
$body | ConvertTo-Json -Depth 3
Output:
{
"data": [
{
"notes": "This is a test of a manual time entry",
"customfield": {
"54138": "IT Services",
"54136": "Yes"
},
"duration": "150",
"type": "manual",
"date": "2021-01-30",
"jobcode_id": "15281216",
"user_id": "John"
}
]
}
EDIT: As robdy mentioned in the comments, the Depth parameter should be used (I've added it). A good explanation can be found here.
I have a function that I want to read data from a json file and return them as they saved in file.
function getTimezones()
{
$timezones = public_path('timezones.json');
$tmp = json_decode(file_get_contents($timezones), true);
return $tmp;
}
The timezones.json file data is like this:
[
{
"value": "Africa/Abidjan",
"text": "Africa/Abidjan"
},
{
"value": "Africa/Accra",
"text": "Africa/Accra"
},
{
"value": "Africa/Algiers",
"text": "Africa/Algiers"
}
]
But when data returns, it's wrapping with file name. Like this:
{
"timezones": [
{
"value": "Africa/Abidjan",
"text": "Africa/Abidjan"
},
{
"value": "Africa/Accra",
"text": "Africa/Accra"
},
{
"value": "Africa/Algiers",
"text": "Africa/Algiers"
}
]
}
I want to get the exact data of json file without timezones wrapper.
I have json files where the various fields can change.
"eventHistory": [{
"occurredAt": "2018-03-17T10:40:05.707 0000",
"calluuid": "G8EMGR6EKD7DLDRP79FOEONVQ4000031",
"eventId": "2018-03-17T10:40:05.707Z_1521283205_G8EMGR6EKD7DLDRP79FOEONVQ4000031",
"event": "Data",
"data": {
"added": {
"OtherTrunkName": "sbc-trunk",
"OriginationDN": "1234",
"BusinessCall": "0",
"OriginationDN_location": "MNLSwitch"
}
}
}, {
"occurredAt": "2018-03-17T10:40:06.033 0000",
"calluuid": "G8EMGR6EKD7DLDRP79FOEONVQ4000031",
"eventId": "2018-03-17T10:40:06.033Z_1521283206_G8EMGR6EKD7DLDRP79FOEONVQ4000031",
"event": "Data",
"data": {
"added": {
"IW_CaseUid": "04d575ba-32e3-48da-8986-a19a6ff493b3",
"IW_BundleUid": "bf3ac19e-e2ea-4d7b-9b48-ef5e17dfdaa1"
}
}
}, {
"occurredAt": "2018-03-17T10:40:10.407 0000",
"calluuid": "G8EMGR6EKD7DLDRP79FOEONVQ4000031",
"eventId": "2018-03-17T10:40:10.407Z_1521283210_G8EMGR6EKD7DLDRP79FOEONVQ4000031",
"event": "Data",
"data": {
"added": {
"WrapUpTime": "0"
},
"deleted": {
"OriginationDN_location": "MNLSwitch",
"OriginationDN": "1234"
}
}
},
Is there an 'easy' way to simply read through and add these as variables to a js. I gather each field and then post to PHP which saves.
then I need to display in a tree... another question likely to appear on that one too.
Any help much appreciated.
It is unclear if you require the variables to be declared in a JS file, or if you simply want each key and value pair to be extracted out. Thus, I've provided 2 approaches that could be useful for your use case.
Suggestion: If it doesn't matter, why not handle the whole JSON object in your PHP save script?
1. Extract Key Value pairs
If you require a recursive JS function to get all the keys and values, you may use this function, referenced from here.
Caveat: This function ignores keys with nested key value pairs, so you will need to modify it to suit your needs.
var json = `
{
"occurredAt": "2018-03-17T10:40:06.033 0000",
"calluuid": "G8EMGR6EKD7DLDRP79FOEONVQ4000031",
"eventId": "2018-03-17T10:40:06.033Z_1521283206_G8EMGR6EKD7DLDRP79FOEONVQ4000031",
"event": "Data",
"data": {
"added": {
"IW_CaseUid": "04d575ba-32e3-48da-8986-a19a6ff493b3",
"IW_BundleUid": "bf3ac19e-e2ea-4d7b-9b48-ef5e17dfdaa1"
}
}
}
`
var obj = JSON.parse(json);
iterate(obj,'');
function iterate(obj, stack) {
for (var property in obj) {
if (obj.hasOwnProperty(property)) {
if (typeof obj[property] == "object") {
iterate(obj[property], stack + '.' + property);
} else {
console.log(property + " " + obj[property]); //get key and value pair here
}
}
}
}
2. Declare Variables in JS
If you require variables to be declared in a JS <script> tag, you can consider using PHP to generate a HTML page with the variables declared.
The code below produces a html file with the following script tag:
Advantage: This approach allows you to get creative, and generate a lot of JS code that is variable specific.
Disadvantage: Debugging this could be hard.
Caveat: The example below is not recursive, so you'll have to do that on your own.
<?php
$string = <<<EOD
{
"occurredAt": "2018-03-17T10:40:06.033 0000",
"calluuid": "G8EMGR6EKD7DLDRP79FOEONVQ4000031",
"eventId": "2018-03-17T10:40:06.033Z_1521283206_G8EMGR6EKD7DLDRP79FOEONVQ4000031",
"event": "Data",
"data": {
"added": {
"IW_CaseUid": "04d575ba-32e3-48da-8986-a19a6ff493b3",
"IW_BundleUid": "bf3ac19e-e2ea-4d7b-9b48-ef5e17dfdaa1"
}
}
}
EOD;
$json = json_decode($string);
echo '<script>';
foreach($json as $key => $value)
{
$output = <<<EOD
var $key = "$value";
EOD;
echo $output;
}
echo '</script>';
?>
I have the following output from a json query and I am looking for a way to search though it and pull the value for the tvdbid(the number 72663) and store it in a variable.
In the example below you can see there are actually 2 results so I would like it to store the both in array.
I am running powershell 3 on my pc so any v3 specific stuff should be ok.
Out put
{
"data": {
"langid": 7,
"results": [
{
"first_aired": "2010-11-15",
"name": "Accused",
"tvdbid": 72663
},
{
"first_aired": "2010-01-17",
"name": "Enzai: Falsely Accused",
"tvdbid": 135881
}
]
},
"message": "",
"result": "success"
}
Using PS V3:
$json = #'
{
"data": {
"langid": 7,
"results": [
{
"first_aired": "2010-11-15",
"name": "Accused",
"tvdbid": 72663
},
{
"first_aired": "2010-01-17",
"name": "Enzai: Falsely Accused",
"tvdbid": 135881
}
]
},
"message": "",
"result": "success"
}
'#
$psobj = ConvertFrom-Json $json
$psobj.data.results.tvdbid
72663
135881
Most of the time I use now the CmdLet given by #mjolinor, but I still use the following old fashion XML serialization in two cases :
1- When I must use PowerShell V2
2- Even in PowerShell V3 when the json returned by a web service is very big the PowerShell V3 is sending an exception.
Add-Type -AssemblyName System.ServiceModel.Web, System.Runtime.Serialization
$utf8 = [System.Text.Encoding]::UTF8
function Write-String
{
PARAM([Parameter()]$stream,
[Parameter(ValueFromPipeline=$true)]$string)
PROCESS
{
$bytes = $utf8.GetBytes($string)
$stream.Write( $bytes, 0, $bytes.Length )
}
}
function Convert-JsonToXml
{
PARAM([Parameter(ValueFromPipeline=$true)][string[]]$json)
BEGIN
{
$mStream = New-Object System.IO.MemoryStream
}
PROCESS
{
$json | Write-String -stream $mStream
}
END
{
$mStream.Position = 0
try
{
$jsonReader = [System.Runtime.Serialization.Json.JsonReaderWriterFactory]::CreateJsonReader($mStream,[System.Xml.XmlDictionaryReaderQuotas]::Max)
$xml = New-Object Xml.XmlDocument
$xml.Load($jsonReader)
$xml
}
finally
{
$jsonReader.Close()
$mStream.Dispose()
}
}
}
function Convert-XmlToJson
{
PARAM([Parameter(ValueFromPipeline=$true)][Xml]$xml)
PROCESS
{
$mStream = New-Object System.IO.MemoryStream
$jsonWriter = [System.Runtime.Serialization.Json.JsonReaderWriterFactory]::CreateJsonWriter($mStream)
try
{
$xml.Save($jsonWriter)
$bytes = $mStream.ToArray()
[System.Text.Encoding]::UTF8.GetString($bytes,0,$bytes.Length)
}
finally
{
$jsonWriter.Close()
$mStream.Dispose()
}
}
}
In your case this will give the following :
$json = #'
{
"data": {
"langid": 7,
"results": [{
"first_aired": "2010-11-15",
"name": "Accused",
"tvdbid": 72663
},
{
"first_aired": "2010-01-17",
"name": "Enzai: Falsely Accused",
"tvdbid": 135881
}]
},
"message": "",
"result": "success"
}
'#
$xmlOut = Convert-JsonToXml -json $json
($xmlOut.root.data.results).ChildNodes[0].tvdbid.InnerText
($xmlOut.root.data.results).ChildNodes[1].tvdbid.InnerText