JSON

960

Solutions

900

Contributors

JavaScript Object Notation, or JSON, is human-readable text used when transmitting data objects consisting of attribute:value pairs between a server and a web application as an alternative to XML. JSON, while it is originally derived from JavaScript, is a language-independent data format. Code for parsing and generating JSON data is available in many programming languages.

Share tech news, updates, or what's on your mind.

Sign up to Post

After going through Ms Access VBA  line by line to try and discover why my posting is not  being recorded on the fake web site I have discovered a clear error  on

 Set JSON = ParseJson(http.responseText)

Open in new window


See my full code here:

Private Sub CmdSales_Click()
  
'  Const SQL_SELECT As String = "SELECT * FROM Qry3;"
  Dim http As Object
  Dim JSON As Object
  Dim coll As VBA.Collection
  Dim dict As Scripting.Dictionary
  Dim db As DAO.Database
  Dim rs As DAO.Recordset
  Dim fld As DAO.Field
  Dim qdf As DAO.QueryDef
  Dim prm As DAO.Parameter
  Set http = CreateObject("MSXML2.XMLHTTP")
  Set db = CurrentDb
  Set qdf = db.QueryDefs("Qry4")
  http.Open "POST", "http://jsonplaceholder.typicode.com/comments, False"
  http.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
  http.setRequestHeader "Content-type", "application/Json"
  http.send ("ConvertToJson(coll, Whitespace:=3)")
  Set JSON = ParseJson(http.responseText)
For Each prm In qdf.Parameters
    prm = Eval(prm.Name)
Next prm
Set rs = qdf.OpenRecordset()

Set qdf = Nothing
  Set coll = New VBA.Collection
'  Set db = CurrentDb
'  Set rs = db.OpenRecordset(SQL_SELECT, dbOpenSnapshot)
  If Not rs.BOF And Not rs.EOF Then
    Do While Not rs.EOF
      Set dict = New Scripting.Dictionary
      For Each fld In rs.Fields
        dict.Add fld.Name, rs.Fields(fld.Name).Value
      Next fld

      coll.Add dict
      rs.MoveNext
    Loop
  End If

  rs.Close
  Set fld = 

Open in new window

0
Learn SQL Server Core 2016
LVL 13
Learn SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

I have a python script on python 3.7.2 that I have pieced together. The script will first accept user input for a string and store into a variable and then iterate through each function call.

Depicted here:

while True:
    uin = input("Please enter a uin or 'enter' to quit: ")
    if not uin:
        break
    startTime = datetime.now()
    selectCustomer(uin)
    selectVehicle(uin)
    selectHRO(uin)
    selectHLABOR(uin)
    selectHPARTS(uin)
    selectINV(uin)
    selectSUPPLIER(uin)
    selectLABOR_OP(uin)
    selectSOURCE(uin)
    selectRO(uin)
    selectLABOR(uin)
    selectPARTS(uin)
    selectEHRO(uin)
    selectEHLABOR(uin)
    selectEHPARTS(uin)
    endTime = datetime.now() - startTime
    print('It took', endTime, ' seconds to run...')

Open in new window


Each function (for the most part is exactly identical and is composed of:

  • opening up a SQL connection
  • running a query
  • storing the output in an ordered dictionary
  • creating a JSON file and naming it with the user input (in our case UIN)
  • closing connection and file

Depicted here:

def selectEHPARTS(uin, output_dir=r"C:\Code\TestData"):
    driver = 'DRIVER={SQL Server};'
    host = 'SERVER=SQL2;'
    database = 'DATABASE=ROWSTAGE;'

    connectionstr = driver + host + database
    conn = pyodbc.connect(connectionstr)
    cursor = conn.cursor()

    cursor.execute("SELECT STORE_UIN, RO_NO, PARTNO, PARTDESC, ITEM_NO, 

Open in new window

0
Hi, I have a PHP script which calls another PHP script via a jQuery ajax call.  I can see that the call is successful and that there is a proper response from the network activity.  However I am having trouble processing that response in the calling PHP/JavaScript code.

Here's my attempt:

demo.html

From the network activity I see the response is:

["data1","data2"] and this is what I am expecting (actual data not shown)

But I cannot 'see' nor process these data in the success data in the calling code shown above.  The alerts do not fire.

Any guidance will be most appreciated and thank you in anticipation.
0
What version of SQL Server introduced JSON support?  
For some reason I'm not finding it any of the JSON docs.microsoft.com pages.

Thanks in advance.
Jim
0
We are now required to process the invoices from Ms Access and then transfer the invoices details to the tax authority in Json format , fair enough . All is okay except the date is always behind by a day after using the Json converter below.

(1) I have attached the screen shoot for the actual invoice dated 13/09/2019 and the converted data into Json, Kindly check the DATE it is always behind by 1 day. Is there a way to sort out this?


'
VBA-JSON v2.3.1
' (c) Tim Hall - https://github.com/VBA-tools/VBA-JSON
'
' JSON Converter for VBA
'
' Errors:
' 10001 - JSON parse error
'
' @class JsonConverter
' @author tim.hall.engr@gmail.com
' @license MIT (http://www.opensource.org/licenses/mit-license.php)
'' ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ '
'
' Based originally on vba-json (with extensive changes)
' BSD license included below
'
' JSONLib, http://code.google.com/p/vba-json/
'
' Copyright (c) 2013, Ryo Yokoyama
' All rights reserved.
'
' Redistribution and use in source and binary forms, with or without
' modification, are permitted provided that the following conditions are met:
'     * Redistributions of source code must retain the above copyright
'       notice, this list of conditions and the following disclaimer.
'     * Redistributions in binary form must reproduce the above copyright
'       notice, this list of conditions and the following disclaimer in the
'       documentation and/or other materials provided with the 

Open in new window

0
Hi Experts,
I have the following Json data in a variable called msg.
How can I  retrieve the key from this data in C#? I want key = "FTPTest/14814-869.txt"

{"Records":[{"eventVersion":"2.1","eventSource":"aws:s3","awsRegion":"us-east-1","eventTime":"2019-09-10T18:10:38.264Z","eventName":"ObjectCreated:Copy",
"userIdentity":{"Test":"AWS:AIDQA"},"requestParameters":{"sourceIPAddress":"179.200.125.2"},
"responseElements":{"x-amz-request-id":"84DAA4BF1A632B7C","x-amz-id-2":"bwJ8Dyykahm16ixDw8VaAtDnriJzzBI+2s04BPQmLCyziAauHUJmVn7pQmuHXe6g="},
"s3":{"s3SchemaVersion":"1.0","configurationId":"Y2IwZjEwNGYtMjRhZi00MTE2LTlhZjMtN2JhMTNlOTg3ODVl","bucket":{"name":"Test",
"ownerIdentity":{"principalId":"AAQWT"},"arn":"arn:aws:s3:::Test"},
"object":{"key":"FTPTest/14814-869.txt","size":184,"eTag":"421b829bc2990a999c64","sequencer":"005D77E711"}}}]}

Open in new window


Thanks in advance!
0
I ask the following question again. Previous one does not answer everything

If I have just a simple web form in html and  a submit button., and I want to create json file basically,
when the button is clicked, capture, each id inside of the form in a loop. (My web form will be huge so I do not want to capture one by one).
then create json format, and  drop into root directory like www.hello.com\json\abc.json.

Is it possible?

In my web form I only use type=text and <select></select> and the id name will be header name  inside of json. Just keep it simple. and I do not use <form></form> just <a onclick=submitnow()>

Thanks,

<div class="col-md-6">
    <div class="form-group bd-t-0-force">
        <label class="form-control-label"><i class="fa fa-credit-card"></i> Card Number: <span class="tx-danger">*</span></label>
        <input class="form-control" type="text" name="ccnumber" value="Market St., San Francisco" placeholder="Enter Card No.">
    </div>
</div><!-- col-8 -->
<div class="col-md-2">
    <div class="form-group mg-md-l--1 bd-t-0-force">
        <label class="form-control-label"><i class="fa fa-credit-card"></i> Card Expiration Month: <span class="tx-danger">*</span></label>
        <input class="form-control" type="text" name="ccexpdatemm" value="" placeholder="Enter Card Expiration Date Month">
    </div>
</div><!-- col-4 -->
<div class="col-md-2">
    <div class="form-group mg-md-l--1 bd-t-0-force">
        <label class="form-control-label"><i 

Open in new window

0
If I have just a simple web form in html and  a submit button., and I want to create json file basically,
when the button is clicked, capture, each id inside of the form in a loop. (My web form will be huge so I do not want to capture one by one).
then create json format, and  drop into root directory like www.hello.com\json\abc.json.

Is it possible?

In my web form I only use type=text and <select></select> and the id name will be header name  inside of json. Just keep it simple. and I do not use <form></form> just <a onclick=submitnow()>

Thanks,

<div class="col-md-6">
    <div class="form-group bd-t-0-force">
        <label class="form-control-label"><i class="fa fa-credit-card"></i> Card Number: <span class="tx-danger">*</span></label>
        <input class="form-control" type="text" name="ccnumber" value="Market St., San Francisco" placeholder="Enter Card No.">
    </div>
</div><!-- col-8 -->
<div class="col-md-2">
    <div class="form-group mg-md-l--1 bd-t-0-force">
        <label class="form-control-label"><i class="fa fa-credit-card"></i> Card Expiration Month: <span class="tx-danger">*</span></label>
        <input class="form-control" type="text" name="ccexpdatemm" value="" placeholder="Enter Card Expiration Date Month">
    </div>
</div><!-- col-4 -->
<div class="col-md-2">
    <div class="form-group mg-md-l--1 bd-t-0-force">
        <label class="form-control-label"><i class="fa fa-credit-card"></i> Card Expiration Year: <span 

Open in new window

0
Dear Experts
Thank you for the valuable help you have rendered to me from inception to now, I’m saying thank you to you all.

Now I still have one more issue which is now 80% done but still require your help. I have done a Json code integration with the help of this site , all I need for now is to include a parameter on the API so that only the specific data can be pulled using “GET”. The VBA code which is working is below and the Json data it is pulling.

Private Sub CmdEmp_Click()
Dim http As Object
    Dim JSON As Object
    Dim i As Integer
    Dim db As DAO.Database
    Dim rs As DAO.Recordset

    Set http = CreateObject("MSXML2.XMLHTTP")
    Set db = CurrentDb
    Set rs = db.OpenRecordset("Contact")
    http.Open "GET", "http://jsonplaceholder.typicode.com/users", False
    http.send
    Set JSON = ParseJson(http.responseText)
    i = 2
    For Each Item In JSON
        With rs
            .AddNew
            ![ID] = Item("id")
            ![FirstName] = Item("name")
            ![UserName] = Item("username")
            ![Email] = Item("email")
            ![City] = Item("address")("city")
            ![Phone] = Item("phone")
            ![WebSite] = Item("website")
            ![Company] = Item("company")("name")
            .Update
        End With
        i = i + 1
    Next
    rs.Close
    Set rs = Nothing
    Set db = Nothing
    Set JSON = Nothing
    Set http = Nothing

    MsgBox ("complete")
End Sub 

Open in new window


Below is the data I’m populating in Ms Access table, for example instead of getting all the users, I want to populate only the selected user ID (txtUserID) from a form. Please note the above code is on onclick event behind the form called frmEmployees which also have the control called (txtUserID).
Here people are required select the user Id and click the command button to populate the exactly required data. Below is the Json data which is required to be populated.


Open in new window

0
After working so hard trying the Json stuff I have managed to make it work in Excel without problems, now I want help to make the same to work Ms Access.
I have created a table called CONTACT with the following controls:
•      ID
•      FirstName
•      Username
•      Email
•      Address
•      City
•      Phone
•      Website
•      Company Name
Below is the code that is working very well in excel:
Public Sub exceljson()
Dim http As Object, JSON As Object, i As Integer
Set http = CreateObject("MSXML2.XMLHTTP")
http.Open "GET", "http://jsonplaceholder.typicode.com/users", False
http.Send
Set JSON = ParseJson(http.responseText)
i = 2
For Each Item In JSON
Sheets(1).Cells(i, 1).Value = Item("id")
Sheets(1).Cells(i, 2).Value = Item("name")
Sheets(1).Cells(i, 3).Value = Item("username")
Sheets(1).Cells(i, 4).Value = Item("email")
Sheets(1).Cells(i, 5).Value = Item("address")("city")
Sheets(1).Cells(i, 6).Value = Item("phone")
Sheets(1).Cells(i, 7).Value = Item("website")
Sheets(1).Cells(i, 8).Value = Item("company")("name")
i = i + 1
Next
MsgBox ("complete")
End Sub

Open in new window


The help I want is to create a query inside the above code so that when I click the button on the form the code can now send the data to the table called CONTACT.
0
OWASP: Forgery and Phishing
LVL 13
OWASP: Forgery and Phishing

Learn the techniques to avoid forgery and phishing attacks and the types of attacks an application or network may face.

Kindly help me to have the listed code below work in Ms Access VBA , I have already imported the JsonBas converter from GTuB site.

Private Sub CmdJson_Click()
Set MyRequest = CreateObject("winhttp.winhttprequest.5.1")
MyRequest.Open "GET", "https://jira.atlassian.com/rest/api/latest/issue/JRA-9"
MyRequest.Send
Dim Json As Object
Set Json = JsonConverter.ParseJson(MyRequest.ResponseText)
MsgBox Json("Key")
End Sub

Open in new window



On My request it say user not defined

I want to have JRA-9 showing after clicking the above button, this part of my training if this works , then the next stage is prepare the Json Spec , I may also ask how to go about it, I'm not worried about opening the record set that used to feed the Json.


JsonCorrection.png

Regards

Chris
0
Hey

$a = @"

{
      "DOG": {
            "experiment": ["right@2", "left@2"],
            "Brown": "AS1"
      }
}

"@

How do I add to experiment? ("experiment": ["right@2", "left@2", "top@2"],],)
How do I edit for example "right@2" to "right@3"

Thanks in advance

Mike
0
Hello everyone.
Im trying to create Stripe payment, well rather Checkout session page. Nothing unclear about their API, well documented and everything.
However, I have a form with 3 fields, one required, other two are not
Now this is when everything is filled in (and it works)
$session = \Stripe\Checkout\Session::create([
            'payment_method_types' => ['card'],
            'billing_address_collection' => 'required',
            'client_reference_id' => $_SESSION['account_id'],
            'customer' => getUserData($link, $_SESSION['account_id'], 'stripe_id'),
            'subscription_data' => [
                'items' => [[
                    'plan' => $_POST['plan']
                ]],
                'metadata' => [
                    'fingerprint' => $fingerprint,
                    'local_account' => $_SESSION['account_id'],
                    'computer_id' => $computerid (this should be removed if field 1 is not posted)
                ],
                'trial_period_days' => '365' (this should be removed if field 2 is not posted)
            ],
            'success_url' => $stripe['success_url'],
            'cancel_url' => $stripe['cancel_url']
        ]);

Open in new window

without making all of the combinations depending on the values from field one used for defining trial_period_days and field two defining stuff in metadata?

Thanks
0
Guys, I am using below cmd to convert a csv to json filw of 50k users

import-csv "usage1.csv" | ConvertTo-Json | Add-Content -Path "dev1json.json"

But I am getting output as below:

[
    {
        "IDNAME":  "user1@domain.com",
         "Property1":  "sales"
    },
    {
        "Idname":  "user2@domain.com",
        "property1":  "Markt"
    },
 {
        "Idname":  "user3@domain.com",
        "Property1":  "fin"
    }
]

  However, the required syntax is:

{
    "value": [
    {

        "Idname":  "user1@domain.com",
        "Property1": "sales",
    },
    {
        "Idname":  "user2@domain.com",
        "Property1": "markt",
    },
    {
        "Idname":  "user3@domain.com",
        "Property1": "Fin",
    }
]
}

This is new for me. Any suggestions what am I doing wrong with the command..
0
I'm programming in c under windows with Microsoft's Visual Studio Code.
I have Codeblock installed as well, and have it's gcc command included in windows path.
Long story short, what I do meantime to execute programs is:
Ctrl+F5 which gives a long message that goes like this:
& 'c:\Users\Anwar\.vscode\extensions\ms-vscode.cpptools-0.25.0\debugAdapters\bin\WindowsDebugLauncher.exe' '--stdin=Microsoft-MIEngine-In-witzbclx.4c0' '--stdout=Microsoft-MIEngine-Out-yg1o05v5.ghu' '--stderr=Microsoft-MIEngine-Error-x2zlssey.ouy' '--pid=Microsoft-MIEngine-Pid-i0pwaoju.tda' '--dbgExe=C://Program Files (x86)//CodeBlocks//MinGW//bin//gdb32.exe' '--interpreter=mi'
Then I type in shell terminal:
gcc main.c
.\main
and the program runs.

I'm looking for how to update launch.json or which ever file to make the whole process automatic like a normal programming environment.
Meaning, I need t ohit Ctrl+F5 for the program to simply run in the terminal, like I once had.


Thank you for your help.
0
Hi Experts

Could you point the reason a value that never evaluates to NULL presents NULL values when creating a JSON file by using PHP?

Accordingly to this code:
<?		
while ($reg6 = $bd1->obtenerRegA()) 
{

	//....
	
	
	$period_name = $reg6['tipo_periodo'];
	
	if(is_null($period_name))
	{	
		// --------------NEVER EVALUATES TO NULLL
		print_r('--NULO---');
	}

	//--------------THIS IS CHECKED TO NOT NULL------------------------------
	if(!empty($period_name) and !is_null($period_name) and $period_name!==" ")
	{
			$period_name = $reg6['tipo_periodo'];
	
			$name =	$reg6['nome_completo'];
			 if(!empty($name) or !is_null($name) or $name!==" ")
				$name = $reg6['nome_completo'];
			 else
				$name ='';


			  // Is this the same professional (or the first)
			  if ($reg6['id_profissional'] !== $id_prof_anterior) 
			  {

				$id_prof_anterior = $reg6['id_profissional'];
				$name = $name;
				$nickname='';  
				$email= $reg6['email_profissional'];
				$cellphone= $reg6['celular_profissional'];
				$cooperativa = $reg6['cooperativa'];
				
				
				$tipo_profissional = '';

				if( $reg6['tipo_periodo']===null or empty( $reg6['tipo_periodo']) or  $reg6['tipo_periodo']===' ' ) 
					$tipo_profissional='';
				 else
					$tipo_profissional=$reg6['tipo_periodo'];
				
				$valor_prof =  $reg6['valor_prof'];
				$gender = $reg6['sexo_profissional'];

				$cpf= $reg6['cpf_profissional'];
				
				if(!empty($email) and !is_null($email) and $email!==" ")
				{
					
				

Open in new window

0
I get the following error:
'd3' is undefined
The Visual Studio 2017 debugger stops on the file, nv.d3.min.js on this segment:
e.dispatch=d3.dispatch("render_start","render_end")

Open in new window

The error occurs right after this line of code in my _Layout.cshtml file:
 @RenderSection("scripts", required: false)

Open in new window

The d3 files referenced on the _Layout.cshtml file were these:
<script src="https://rawgit.com/mbostock/d3/master/d3.min.js"></script>
<script src="https://rawgit.com/novus/nvd3/v1.1.15-beta/nv.d3.min.js"></script>
<script src="https://rawgit.com/krispo/angular-nvd3/v0.1.1/dist/angular-nvd3.js"></script>

Open in new window

I noticed that one of them was a beta version so I changed it to this:
    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/1.29.5/d3.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/1.29.5/d3.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-nvd3/1.0.9/angular-nvd3.min.js"></script>

Open in new window

But then I started getting bootstrap errors like this one in my angular.js [dynamic] file :
Unhandled exception at line 1290, column 7 in https://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.js
0x800a139e - JavaScript runtime error: [ng:btstrpd] App Already Bootstrapped with this Element '<div class="col-lg-12 ng-scope" ng-controller="summaryCtrl" ng-app="surveyApp">'
http://errors.angularjs.org/1.2.8/ng/btstrpd?p0=%3Cdiv%20class%3D%22col-lg-12%20ng-scope%22%20ng-controller%3D%22summaryCtrl%22%20ng-app%3D%22surveyApp%22%3E occurred
That happens in this area of code:
function bootstrap(element, modules) {
  var doBootstrap = function() {
    element = jqLite(element);

    if (element.injector()) {
      var tag = (element[0] === document) ? 'document' : startingTag(element);
      throw ngMinErr('btstrpd', "App Already Bootstrapped with this Element '{0}'", tag);
    }

Open in new window

I'm not sure if changing the CDN source of the d3.js files caused that because of incompatibility or if there is a different reason. I think that at this point, since I don't know what I'm doing, the more I try to fix it, the more I'm going to break it.
I did not create this app. I inherited it from a programmer that is no longer available.
0
Experts!

I am an entry-level programmer and quickly learning python. I am having difficulty understanding a few concepts. In the code below, I have created a script that will establish a connection string, query a database, and output the data in a pretty format in JSON.

I am looking to understand how I would incorporate:

  • adding in an iteration that will iterate strings from user input (I understand how to ask for user input and how to put those items in array or object) but grabbing the contents of the array and storing them in place of store_uin = (instead of CO004 inserting what would be in the array)
  • iterating and repeating those select statements for all the contents in the array
  • and writing out to new output JSON file instead of overriding one with the file name being export_name from array_date.JSON

import pyodbc
import json
import collections
def selectHRO():
    driver = 'DRIVER={SQL Server};'
    host = 'SERVER=hostname;'
    database = 'DATABASE=dbname;'

    connectionstr = driver+host+database
    conn = pyodbc.connect(connectionstr)
    cursor = conn.cursor()

    cursor.execute("SELECT cust_NO, FNAME, LNAME, store_UIN from Customer where store_UIN = 'CO004'")

    rows = cursor.fetchall()

    objects_list = []
    for row in rows:
        d = collections.OrderedDict()
        d['cust_NO'] = row.cust_NO
        d['FirstName'] = row.FNAME
        d['LastName'] =

Open in new window

0
Dear Experts,
I use PHP 7.3.

I use a SMS service which is working with CURL, however, in this CURLOPT_POSTFIELD I have 3 diffrent messages.
Obviously I would like to send only my mesaj which is $mesaj

$gonderen is my name
$gsmno is my mobile number
$mesaj is my message

this below Postfield has 3 messages with 3 diffrent receivers. I want to send the first message which is mine.
I couldn't properly cut it. Help is needed. Thank you.

CURLOPT_POSTFIELDS => "{\r\n\t\"bulkId\":\"BULK-ID-123-xyz\",\r\n\t\"messages\":[\r\n\t\t{\r\n\t\t\t\"from\":\"".$gonderen."\",\r\n\t\t\t\"destinations\":[\r\n\t\t\t\t{\r\n\t\t\t\t\t\"to\":\"".$gsmno."\",\r\n\t\t\t\t\t\"messageId\":\"MESSAGE-ID-123-xyz\"\r\n\t\t\t\t},\r\n\t\t\t\t{\r\n\t\t\t\t\t\"to\":\"45644564567\"\r\n\t\t\t\t}\r\n\t\t\t],\r\n\t\t\t\"text\":\"".$mesaj."\",\r\n\t\t\t\"flash\":false,\r\n\t\t\t\"language\":{\r\n\t\t\t\t\"languageCode\":\"TR\"\r\n\t\t\t},\r\n\t\t\t\"transliteration\":\"TURKISH\",\r\n\t\t\t\"intermediateReport\":true,\r\n\t\t\t\"notifyUrl\":\"https://www.example.com/sms/advanced\",\r\n\t\t\t\"notifyContentType\":\"application/json\",\r\n\t\t\t\"callbackData\":\"DLR callback data\",\r\n\t\t\t\"validityPeriod\": 720\r\n\t\t},\r\n\t\t{\r\n\t\t\t\"from\":\"41793026700\",\r\n\t\t\t\"destinations\":[\r\n\t\t\t\t{\r\n\t\t\t\t\t\"to\":\"41793026785\"\r\n\t\t\t\t}\r\n\t\t\t],\r\n\t\t\t\"text\":\"A long time ago, in a galaxy far, far away... 

Open in new window

0
Starting with Angular 5
LVL 13
Starting with Angular 5

Learn the essential features and functions of the popular JavaScript framework for building mobile, desktop and web applications.

Hi Experts

Could you check what is needed to be adjusted on this PHP code to make it generates a JSON as an array under an object (not another separated object) ?

Acordingly to
//------------------------------------
// -- Actual JSON obtained by the code
//------------------------------------
{
		"name": "Wagner XXXXXX",
		"nickname": "",
		"email": " ",
		"roles": [
			"professional"
		],
		"internal_id": "CONS:-",
		"cellphone": "11941163485",
		"tags": [
			"COOP:MULTISA",
			"FUNC:Aux. Enfermagem",
			"TIPO_PAGAMENTO:",
			"VALOR:R$0"
		],
		"gender": "masculino",
		"send_invite_when_submit": true,
		"shifts": {
			"date": "2012-12-16",
			"period_name": "Aux. Enfermagem",
			"tags": [
				"ESC:"
			]
		}
	}, // Not to close the object
	{  // Just open an array of shifts objects here.
		"shifts": {
			"date": "2012-12-18",
			"period_name": "Aux. Enfermagem",
			"tags": [
				"ESC:"
			]
		}
	},
	{
		"shifts": {
			"date": "2012-12-20",
			"period_name": "Aux. Enfermagem",
			"tags": [
				"ESC:"
			]
		}
	},
	
//---------------
// -- Needed JSON
//---------------	
{
		"name": "Vinicius",
		"nickname": "Vinicius",
		"email": "vinicius@teste.com",
		// se trabalha na escala, é professional,
		// se é gestor (escalista), é manager
		"roles": [
			"organizador",
			"plantonista"
		],
		"internal_id": "c2917",
		"cellphone": "11-988888889",
		"tags": [
			"tag1", "tag2", "COOPERATIVA-NOME_COOPERATIVA"
		],
		"gender": "male",
		"send_invite_when_submit": true,
		

Open in new window

0
Hi Experts

Could you point what must to be corrected at this PHP code to make it correctly generates the needed JSON code?

Accordingly to:
<?
$prof_anterior = '';
						
while ($reg3 = $bd1->obtenerRegA())
{						
	//....
	
	// Checks if the id_profissional changed
	if( $reg3['id_profissional'] !== $prof_anterior )
	{

            // If changed mount completelly the object					
			$obj->professionals = array(
										array('name'=>$reg3['nome_completo'],
											  'nickname'=>'',
											  'roles'=>array($papel),
											  'internal_id'=>"CONS:".$conselho.'-'.$identificador_interno,
											  'cellphone'=>$reg3['celular_profissional'],
											  'tags'=>array("COOP:".$reg3['cooperativa'],
											  "FUNC:".$reg3['tipo_profissional'],
											  "TIPO_PAGAMENTO:".$tipo_pagamento,
											  "VALOR:R$".$reg3['valor_prof']),
											  "gender"=>$reg3['sexo_profissional'], 
											  "send_invite_when_submit"=>true,
											  'shifts' => $shifts)  // I guess at this point a for/ next must to be implemented to mount all the shift related to 'id_profissional', following the rule, but I don't know how to implement it..
										  );
		
			$schedules[] = $obj; //add each object to the array
	}
	else
	{		
			// Just add another object, not completelly the new array
			$shift_prof->shifts =  $shifts;	
			$schedules[] = $shift_prof; //add each object to the array
	}

    // Goes to the next id_profissional 
	$prof_anterior = 

Open in new window

0
Hi Experts

Could you point what must to be corrected on this PHP code to consider correctly the array adition when assembling a JSON file?

The resumed code, the relevant part is assigned (lines 204 /  218)
<?
//...
	
try 
	{
	
		$periods = array();
		$professionals = array();
		$gerenciador='';	
		$dias_da_semana_excecao = array();

		  $query2 = "SELECT DISTINCT TOP 1 p.id_paciente, p.nome, e.endereco, TRY_CAST(e.numero as VARCHAR) as numero, e.complemento, e.bairro, e.cidade, e.uf, RTRIM(e.cep) as cep , g.gerenciador,";
		  $query2.= "  	CASE WHEN TRY_CAST(SUBSTRING (e.cep ,1 , 5 ) AS INT) BETWEEN 1000 AND  01599    THEN 'CE'";
		  $query2.= "  	...";
		  $query2.= "		 WHEN TRY_CAST(SUBSTRING (e.cep ,1 , 5 ) AS INT) BETWEEN 11000 AND 11249   THEN 'Santos'";  
		  $query2.= "		 WHEN TRY_CAST(SUBSTRING (e.cep ,1 , 5 ) AS INT) BETWEEN 20000 AND 23799   THEN 'Rio de Janeiro'";  
		  $query2.= "	 ELSE 'INDEFINIDO' END  AS regiao";
		  $query2.= " FROM XXXXX.dbo.pacientes p WITH(NOLOCK)";
		  $query2.= "		INNER JOIN  XXXXX.dbo.paciente_endereco pe WITH(NOLOCK) ON p.id_paciente = pe.id_paciente ";
		  $query2.= "		INNER JOIN  XXXXX.dbo.enderecos e WITH(NOLOCK) ON pe.id_endereco = e.id_endereco ";
		  $query2.= "		INNER JOIN  XXXXX.dbo.internacao i WITH(NOLOCK) ON p.id_paciente = i.id_paciente";
		  $query2.= "		INNER JOIN  XXXXX.dbo.contratos c  WITH(NOLOCK) ON i.id_contrato = c.id_contrato";
		  $query2.= "       INNER JOIN XXXXX.dbo.gerenciadores g WITH(NOLOCK) ON 

Open in new window

0
Hi,

Please see https://www.experts-exchange.com/questions/29154913/Powershell-and-jsons-to-a-Mongodb-PS-management-mongodb-itemd.html

I would like to have a jumpstart on PowerShell, MongoDB and jsons I have.

So I import the Powershell module, have my MongoDB, then please help me with a basic script.
$MyMongoDBServer
Connect-To $MyMongoDBServer
Then what? Create a database or just import the jsons in bulk, foreach path get-content path convert to json then import?
Then how do I read it via Powershell

Dont have any mongodb knowledge, Powershell I do know pretty well.
Could you show me a working example script of how it is done?

J

J
0
I am updating records using sequelize. I am testing the backend with postman.  The code seems to work as there is no error however when testing it in postman, no rows are affected (updated). I have used both put and patch methods, however, I received the same results. Perhaps, there is an error in the code that I am missing.

Here is the code:

router.put('/editstation/:id', (req, res) => {

             let newStation = req.body.station;
             let newAddress = req.body.address;
             let newMonthlycstoresales = req.body.monthlycstoresales;
             let newOperator = req.body.operator;
             let newTopsku = req.body.topsku;


   
   let values = {Station: newStation, Address: newAddress, monthlycstoresales: newMonthlycstoresales, Operator: newOperator, topsku:newTopsku};

   let selector = {
       where: {id: req.params.id}
   }
   Store.update(values, selector)
   .then((updatedPost)=>{
       console.log(updatedPost);
       res.json({
           "message": updatedPost
       })
   })
   .catch(err => {
       res.json({
           "message": err
       })
   })

});

Here is the json test in postman

{
      "ID": 6,
      "Station": "Rargain jiack",
      "Operator": "Dilly"
}

Here are the results:

{
    "message": [
        0
    ]
}
0
Hi,

I have a lot of json files which contain data of software: name, vendor, date requested, date packaged, metadata like description, where to download etc.
I add this data automated via Powershell.
I do query the files regularely but this takes to much time (to many files).

I have a MongoDB on a Linux server and would like to move the jsons to this mongodb.

Please advise howto do this via Powershell: add/remove jsons, query mongodb, adjust/asd/remove item in mongodb

J
0

JSON

960

Solutions

900

Contributors

JavaScript Object Notation, or JSON, is human-readable text used when transmitting data objects consisting of attribute:value pairs between a server and a web application as an alternative to XML. JSON, while it is originally derived from JavaScript, is a language-independent data format. Code for parsing and generating JSON data is available in many programming languages.