Getting data from JSON in node-red with http request - json

Disclaimer: this is my first time attempting to write in Javascript; I don't know what I am doing.
I tried looking for example of this, but everything I found has the JSON object included in Javascript. Trying to return just the price_usd from this JSON
https://api.coinmarketcap.com/v1/ticker/bitcoin/
[
{
"id": "bitcoin",
"name": "Bitcoin",
"symbol": "BTC",
"rank": "1",
"price_usd": "972.935",
"price_btc": "1.0",
"24h_volume_usd": "501202000.0",
"market_cap_usd": "15650425175.0",
"available_supply": "16085787.0",
"total_supply": "16085787.0",
"percent_change_1h": "-2.35",
"percent_change_24h": "-17.36",
"percent_change_7d": "2.55",
"last_updated": "1483690766"
}
]
My current code in the linked function box is :
return {payload:msg.payload.price_usd};
msg.payload returns undefined. Tried with both http request set to return as parsed JSON object and as UTF-8 string.

The response is surrounded by [ ]. This indicates it's an array. So you need to reference into that array to get to the data.
msg.payload[0].price_usd

Related

Executing a specific http method 'depending' on the condition given in the JSON file

I was thinking about the possibility of executing a specific http method (POST or PUT) in POSTMAN without specifying it.
I mean; imagine if there was a field in a JSON file called: METHOD within 2 possible states: 'I' corresponding to INSERT OR POST and the another one: 'U' related to UPDATE or PUT
Something like this: (please, do note the field called "method"):
[
{
"sku": "95LB645R34ER",
"method": 'I'
"payload": {
"price": "147000",
"tax_percentage": "US-21",
"store_code": "B2BUSD",
"markup_top": "1.62",
"status": "1",
"group_prices": [
{
"group": "CLASS A",
"price": "700038.79",
"website": "B2BUSD"
}
]
}
},
{
"sku": "95TYS34344ER",
"method": 'U'
"payload": {
"price": "69978",
"tax_percentage": "US-21",
"store_code": "B2BUSD",
"markup_top": "9.99",
"status": "1",
"group_prices": [
{
"group": "CLASS B",
"price": "88888.79",
"website": "B2BUSD"
}
]
}
}
]
I would like to run that JSON using the Collection Runner but i have no idea how to do the trick. I mean, everytime i generate a collection i have to specify the HTTP METHOD otherwise it wont know what to do.
I want the program to adjust that by looking at the JSON file, if "method":'I' then, perform a POST or if "method":'U' execute a PUT method. Do you get me?
I've been reading the documentation but i did not find something like that or maybe i did not understand. I'm not an expert on POSTMAN :(
Can you help me?
EDIT:
Alright, i did this:
In the request UI, use the {{METHOD}} syntax where you would see the HTTP method. This is an editable field as it allows you to add custom HTTP methods.
In the file, use the METHOD key and any HTTP verb as the value. Ensure that it's part of each object in the datafile as you will need it for each iteration.

JMeter - JSON Extractor extracts correct value in one case but null in other case

I have two requests that return response with similar JSON structure. When I try to use JSON extractor on one, it works properly but when I try to extract value in the same way from the second one, it doesn't work. But let's cut to the chase.
My first response looks like this:
{
"values": [
{
"id": 1,
"name": "Fendi",
"logoId": null,
"belongsToUser": true
},
{
"id": 2,
"name": "Jean Paul Gaultier",
"logoId": null,
"belongsToUser": true
},
{
"id": 3,
"name": "Nike",
"logoId": null,
"belongsToUser": false
},
{
"id": 4,
"name": "Adidas",
"logoId": null,
"belongsToUser": true
}
]
}
And I try to extract ID of the object that "belongsToUser": false in this JSON Extractor:
JSON path expression: values[?(#.belongsToUser == false)].id
Match No.: 0
Default Values: null
And it works perfecty fine.
However, when I try this way on my second response, it doesn't work.
The response looks like this:
{
"values": [
{
"id": 12,
"brandName": "Fendi",
"productCategoryName": "Shoes",
"size": "38",
"colorNames": [
"color_green"
],
"date": 1536537600000,
"imageId": null,
"title": "Money",
"numberOfOffers": 0,
"status": "ONGOING"
},
{
"id": 13,
"brandName": "Fendi",
"productCategoryName": "Shoes",
"size": "38",
"colorNames": [
"color_green"
],
"date": 1536537600000,
"imageId": null,
"title": "Exchange",
"numberOfOffers": 0,
"status": "ONGOING"
}
]
}
I try to get id of object that has title variable = "Money" with JSON extractor:
JSON path expression: values[?(#.title == 'Money')].id
Match No.: 0
Default Values: null
But it doesn't find id value and sets my JMeter variable to null.
I also tried to leave Money unquoted or in double quotes and tried different JSON path expresions, like
$.values[?(#.title == 'Money')].id
$..[?(#.title == 'Money')].id
$.[?(#.title == 'Money')].id
But none of these seems to work. Do you have any idea how my JSON path expression shoud look to work properly?
And why doesn't it work in second case when it works in first? Is it because objets in second response have inside array?
I have used your code and it is giving the correct results. Please check the below images.
I have tried with version 3.1 also and it is working fine.
Hope this helps.
Check the below image for different types of options in view result tree.
The $..[?(#.title == 'Money')].id expression should work just fine:
Most probably your JMeter installation is corrupt and you experience some form of jar hell due to some clashing library in JMeter Classpath (it might be caused by presence of deprecated JSON Plugins or similar) . So I would recommend obtaining clean latest version of JMeter and trying out your test on it. If you're using any plugins - install them using JMeter Plugin Manager
If you are not in position to re-install JMeter you can try to get to the bottom of the issue by looking into jmeter.log file. If there are no suspicious entries - add the next line to log4j2.xml file:
<Logger name="org.apache.jmeter.extractor.json" level="debug" />

Get JSON in web api and get the specific data from JSON

How can I fetch the json into web api and get the specific data?
For example, this is my web api "https://api.coinmarketcap.com/v2/ticker/1/" and the output is like this:
{
"data": {
"id": 1,
"name": "Bitcoin",
"symbol": "BTC",
"website_slug": "bitcoin",
"rank": 1,
"circulating_supply": 17145625.0,
"total_supply": 17145625.0,
"max_supply": 21000000.0,
"quotes": {
"USD": {
"price": 6196.07,
"volume_24h": 3623440000.0,
"market_cap": 106235492694.0,
"percent_change_1h": -0.08,
"percent_change_24h": -2.9,
"percent_change_7d": -6.64
}
},
"last_updated": 1531423345
},
"metadata": {
"timestamp": 1531423031,
"error": null
}
}
I want a code how I can open the "web api link", "get the json into web api", "get the data in json".
I'm not really sure what language you are using. It would be helpful to provide that information in the tags or the question itself
If you are using python 3.7
import json
from urllib.request import urlopen
myjson = JSON.loads(urlopen("https://api.coinmarketcap.com/v2/ticker/1/"))
Here you will get the json deserialized into native python nested arrays and dictionaries (dictionaries in your case).
From this you can access elements from the json just like you would any element from a normal python dictionary. For example if I wanted to access the id
myjson["data"]["id"]
Hope this helped! Best of luck... please reply what language you are using and any frameworks so the community can help you in the best way.

JMeter mock json response

Is there a way to make a request on JMeter and receive a mocked JSON response that I create, for example:
[
{
"Car": "BMW",
"Model": "520D",
"Color": "Black"
},
{
"Car": "Audi",
"Model": "A3",
"Color": "Red"
},
{
"Car": "Ford",
"Model": "Focus",
"Color": "Blue"
}
]
I need a mocked up response that I can practice on using JMeter samplers etc.
If you want to mock the entire request/response use Dummy Sampler, just set Response Data field with your JSON and it'll return it:
If you want to mock only the response, meaning send to a real server the request, see mock http request answer Which suggests using a third party, as WireMock or mock-server.com as #Kiril S. suggested in comments
Another option is to manipulate response using JSR223 PostProcessor
Use SampleResult.setResponseData to set JSON, for example:
prev.setResponseData("[ { \"Car\": \"BMW\" }]","UTF-8");

printing json values python

This is my json result from the request
{
"name": "North America",
"region_tag": "na1",
"hostname": "prod.na1.lol.riotgames.com",
"services": [
{
"status": "online",
"incidents": [
{
"active": true,
"created_at": "2018-03-22T10:53:03.397Z",
"id": 7636
}
]
}
]
}
I want to print out the value of status from services
My code
link = "https://na1.api.riotgames.com/lol/status/v3/shard-data?api_key={}".format(API_KEY)
rq_link=rq.get(link).text
rq_json=json.loads(rq_link)
I've tried
print(rq_json['services']['status])
and I get an error saying TypeError: list indices must be integers or slices, not str
Is there another way to do it other than using the for loop
for post in rq_json['services']:
print(rq_json['status'])
The answer you're looking for its
rq_json['services'][0]['status']
Because, the service part is described in a list, you need to specify an index to get into inner dict
You can use list comprehension:
[print(service['status']) for service in rq_json['services']]
More info about list comprehension could be found in the official Python documentation