Nested object in form data - form-data

I'm trying to do a post request with an object inside an object. My JSON body should look like this:
{ "name": "Dish name",
"description": "Dish description",
"allergies": "Dish allergies",
"price": "12",
"category": { "id": "1",
"name":"Category name",
"description": "Category description"
},
"image":"adasd"
}
First I JSON.stringify the category object then I create the whole object using the useForm hook in React, after the submit the object creates succesfully but the category has backslashes. I can try to remove the backslashes but he keeps wrapping the object in " " it will look like this:
"category": "{ "id": "1",
"name":"Category name",
"description": "Category description"
}",
If I try to post this body it will give an error because it is not seen as an object.
How can I bypass this effect does someone know?

Related

How to get only specific fields with Google Directory API users.list

The documentation (https://developers.google.com/admin-sdk/directory/reference/rest/v1/users/list#query-parameters) says you can use customFieldMask to get only specific fields. I cannot figure out the format/structure of this property.
For example, given this for a user:
{
"kind": "admin#directory#user",
"id": "...",
"etag": "\"...\"",
"primaryEmail": "...",
"name": {
"givenName": "...",
"familyName": "...",
"fullName": "......"
},
"emails": [
{
"address": "...",
"primary": true
}
]
}
I only want to get primaryEmail but I can't figure out how.
Send "users(primaryEmail)" in the fields parameter, not in the customFieldMask parameter.
The Directory API can't retrieve the 'primaryEmail' with the customFieldMask attribute, with this attribute you can only specify the custom schema names that you create in the Admin console.

How to simulate multiple child elements with different values in the same Jmeter POST request body?

The below request being the base request,
[
{
"name": "Test1",
"description": "testings",
"unitname": simple,
"ID": 02,
"val": "item"
},
{
"name": "Test2",
"description": "testing",
"unitname": simple3,
"ID": 23,
"val": "item"
}
]
I want to simulate this with multiple (1000) 'child' sections like the below in a single JMeter request:
It should create 1000 data set(name,description,unitname,ID,val) with unique values and then post the request. Instead of manually creating multiple tags, can i automate it or create a script to generate this automatically ?
[
{
"name": "Test1",
"description": "testings",
"unitname": simple,
"ID": 02,
"val": "item"
},
{
"name": "Test2",
"description": "testing",
"unitname": simple3,
"ID": 23,
"val": "item"
}
{
"name": "Test3",
"description": "testing",
"unitname": simple4,
"ID": 23,
"val": "item"
}
{
"name": "Test4",
"description": "testing",
"unitname": simple6,
"ID": 23,
"val": "item"
}
]
Any help please?
Add JSR223 PreProcessor as a child of your request where you need to send the generated JSON
Put the following code into "Script" area:
import groovy.json.JsonBuilder
import groovy.json.internal.LazyMap
import org.apache.commons.lang3.RandomStringUtils
def data = new ArrayList()
1.upto(1000, {
def entry = new LazyMap()
entry.put('name', 'test' + it)
entry.put('description', RandomStringUtils.randomAlphabetic(10))
entry.put('unitname', 'simple')
entry.put('ID', it)
entry.put('val', 'item')
data.add(entry)
})
def builder = new JsonBuilder()
builder(
data.collect {
[
name : it.get('name'),
descrtiption: it.get('description'),
unitname : it.get('unitname'),
ID : it.get('ID'),
val : it.get('val')
]
}
)
sampler.setPostBodyRaw(true)
sampler.addNonEncodedArgument("", builder.toPrettyString(), "")
Tick Cache compiled script if available box
Make sure groovy is selected in "Language" dropdown
That's it, the above script will generate a JSON Array and set it as the HTTP Request sampler's body.
More information:
Groovy: Parsing and producing JSON
Apache Groovy - Why and How You Should Use It

How to edit nested data with admin on rest?

I don't know how to handle nested data with admin on rest.
My GET request returns the full object without additional calls for filters and thumbnails (see below).
Example object:
{
"id": "58bd633e4b77c718e63bf931",
"title": "Project A",
"description": "Blabla",
"image": "https://placeholdit.imgix.net/~text?txtsize=33&txt=350%C3%97150&w=350&h=150",
"disable": false,
"filters": [
{
"id": "58c662aa4ea73e3d4373dad7",
"filterValue": {
"label": "Filter value",
"color": "#0094d8",
"id": "58c7999162700623b4aac559"
},
"isMain": true
}
],
"thumbnails": [
{
"id": "58bfeac780021c56cc71bfac",
"image": "http://lorempixel.com/1024/768/",
"description": "Bla",
"device": "desktop"
},
{
"id": "58bfeacf80021c56cc71bfad",
"image": "http://lorempixel.com/800/600/",
"description": "Bla",
"device": "laptop"
}
]
}
My first idea was to create custom Input Components but I don't know if it's the best solution? Any ideas or examples?
Admin-on-rest relies on redux-form, which supports nested attributes. Just set the source of your input as the path to the nested property, with dot separator:
<TextInput source="foo.bar" />
For your filters and thumbnails, you'll have to use redux-form's <Fields> component, and create a custom input component with it.

Shopify API: Importing a JSON formatted list of products through a private app

Essentially I have a file with a list of products I would like to add to my shopify store, I'm fairly certain it's formatted correctly although if it isn't please tell me what to fix. I was wondering how using a POST request through a private app I could get these onto my store. The file looks like this:
{
"product": {
"title": "TITLE HERE",
"body_html": "DESCRIPTION HERE",
"vendor": "VENDOR HERE",
"product_type": "PRODUCT TYPE HERE",
"variants": {
"option1": "Default",
"price": "PRICE HERE"
},
"images": {
"src": "LINK TO IMAGE HERE"
}
},
"product": {
"title": "TITLE HERE",
"body_html": "DESCRIPTION HERE",
"vendor": "VENDOR HERE",
"product_type": "PRODUCT TYPE HERE",
"variants": {
"option1": "Default",
"price": "PRICE HERE"
},
"images": {
"src": "LINK TO IMAGE HERE"
}
},
"product": {
"title": "TITLE HERE",
"body_html": "DESCRIPTION HERE",
"vendor": "VENDOR HERE",
"product_type": "PRODUCT TYPE HERE",
"variants": {
"option1": "Default",
"price": "PRICE HERE"
},
"images": {
"src": "LINK TO IMAGE HERE"
}
},
and so on...
This file is named "products.json". Is there any POST request that would allow me to just submit this file, or would I have to process and break it down somehow and feed it to the API using PHP or Ruby...I spent the greater part of a day extracting all 500+ products out of a corrupted MySQL CMS backup and getting them all cleaned up in JSON (using PHP and some regex), so a pain free solution would be much appreciated.
You cannot submit multiple products to be created at once, they need to be submitted individually. The docs you already linked to explain all the available API endpoints and the format for the data.
You can store these products in database and by creating a connection from database you can add multiple products at a time by defining one array and its value will be fetched from database.

Edit parsed JSON

I have a JSON file contact.txt that has been parsed into an object called JSONObj that is structured like this:
[
{
"firstName": "John",
"lastName": "Smith",
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021"
},
"phoneNumbers": [
{ "type": "home", "number": "212 555-1234" },
{ "type": "fax", "number": "646 555-4567" }
]
},
{
"firstName": "Mike",
"lastName": "Jackson",
"address": {
"streetAddress": "21 Barnes Street",
"city": "Abeokuta",
"state": "Ogun",
"postalCode": "10122"
},
"phoneNumbers": [
{ "type": "home", "number": "101 444-0123" },
{ "type": "fax", "number": "757 666-5678" }
]
}
]
I envision editing the file/object by taking in data from a form so as to add more contacts. How can I do this?
The following method for adding a new contact to the JSONObj's array doesn't seem to be working, what's the problem?:
var newContact = {
"firstName": "Jaseph",
"lastName": "Lamb",
"address": {
"streetAddress": "25 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "13021"
},
"phoneNumbers": [
{ "type": "home", "number": "312 545-1234" },
{ "type": "fax", "number": "626 554-4567" }
]
}
var z = contact.JSONObj.length;
contact.JSONObj.push(newContact);
It depends on what technology you're using. The basic process is to read the file in, convert it to whatever native datatypes (hash, dict, list, etc.) using a JSON parsing library, modify or add data to the native object, then convert it back to JSON and store it to the file.
In Python, using the simplejson library it would look like this:
import simplejson
jsonobj = simplejson.loads(open('contact.txt'))
#python's dict syntax looks almost like JSON
jsonobj.append({
'firstName': 'Steve',
'lastName': 'K.',
'address': {
'streetAddress': '123 Testing',
'city': 'Test',
'state': 'MI',
'postalCode': '12345'
},
'phoneNumbers': [
{ 'type': 'home', 'number': '248 555-1234' }
]
})
simplejson.dump(jsonobj, open('contact.txt', 'w'), indent=True)
The data in this example is hardcoded strings, but it could come from another file or a web application request / form data, etc. If you're doing this in a web app though I would advise against reading and writing to the same file (in case two requests come in at the same time).
Please provide more information if this doesn't answer your question.
In response to "isn't there way to do this using standard javascript?":
To parse a JSON string in Javascript you can either eval it (not safe) or use a JSON parser like this one's JSON.parse. Once you have the converted JSON object you can perform whatever modifications you want to it in standard JS. You can then use that same library to convert a JS object to a JSON string (JSON.stringify). Javascript does not allow file access (unless you're doing serverside JS), so that would prevent you from reading & writing to your contact.txt file directly. You'd have to use a serverside language (like Python, Java, etc.) to read and write the file.
Once you have read in the JSON, you just have an associative array - or rather you have a pseudo-associative array, since this is Javascript. Either way, you can treat the thing as one big list of dictionaries. You can access it by key and index.
So, to play with this object:
var firstPerson = JSONObj[0];
var secondPerson = JSONObj[1];
var name = firstPerson['firstName'] + ' ' + firstPerson['lastName'];
Since you will usually have more than two people, you probably just want to loop through each dictionary in your list and do something:
for(var person in jsonList) {
alert(person['address']);
}
If you want to edit the JSON and save it back to a file, then read it into memory, edit the list of dictionaries, and rewrite back to the file.
Your JSON library will have a function for turning JSON into a string, just as it turns a string into JSON.
p.s. I suggest you observe JavaScript conventions and use camelcase for your variable names, unless you have some other customs at your place of employment. http://javascript.crockford.com/code.html

Resources