Parsing JSON with AFNetworking give results with round brackets - xcode

Here is the simplified JSON file, I need to download it from a net service and parse results in a table!
EDIT: I provide now more precise code, cleaned and formatted by online tool:
{
"main": [
{
"id": 0, <--- float value
"type": "type0", <--- STRING value
"valueA": {
"valueA1": 1, <--- float value
"valueA2": 2, <--- float value
"valueA3": 3 <--- float value
},
"valueB": {
"valueB1": 1, <--- float value
"valueB2": 2 <--- float value
},
"valueC": [
{
"valueC1": "string0C1", <--- STRING value
"valueC2": 2, <--- float value
"valueC3": 3, <--- float value
}
]
},
FORMATTED by online tool jsonviewer.stack.hu:
I need to parse it with AFJSONRequestOperation, and I write this code:
NSMutableArray *main = [JSON objectForKey:#"main"];
arrayID = [main valueForKey:#"id"];
arrayType = [main valueForKey:#"type"];
NSMutableArray *arrayValueC = [main valueForKey:#"valueC"];
NSMutableString *stringC1 = [arrayValueC valueForKey:#"valueC1"];
// I CANT USE objectForKey, XCode give an exception -[__NSArrayI objectForKey:]: unrecognized selector sent to instance
NSLog(#"id: %#",arrayID);
NSLog(#"type: %#",arrayType);
NSLog(#"string: %#",stringC1);
When I parse, I get this results from NSLog:
id: (
0,
1,
2,
3,
4,
5,
6,
7,
8,
9
)
type: (
type0,
type1,
type2,
type3,
type4,
type5,
type6,
type7,
type8,
type9
)
string: (
(
"string0C1"
),
(
"string2C1"
),
(
"string2C1"
),
(
"string3C1"
),
(
"string4C1"
),
(
"string5C1"
),
(
"string6C1"
),
(
"string7C1"
),
(
"string8C1"
),
(
"string9C1"
)
)
As u can see its all perfect, I can extrapolate every value of ID (float) and TYPE (string), but I hate the round brackets in every object of the valueC1 string: how can I get the clean valueC1 without brackets and quotation marks? Please if u can provide some code. Thanks!

Don't use valueForKey:. Use objectForKey: instead. This is probably the major problem. But once you use it, you might run into new problem:
The following contains a problem that will manifest itself when arrayValueA is accessed the first time:
NSMutableArray *arrayValueA = [arrayMain objectForKey:#"valueA"];
The element stored at valueA is an object i.e. a dictionary and not an array.
Finally, your simplified JSON is invalid anyway. Several values are missing double quotes, e.g.:
"id": id0
should be:
"id": "id0"
You better shows the real JSON data and the real code.
Update:
You should be able to access the JSON data with the following code:
NSArray *main = [JSON objectForKey:#"main"];
NSDictionary* main0 = [main objectAtIndex:0];
arrayID = [main0 objectForKey:#"id"];
arrayType = [main0 objectForKey:#"type"];
NSArray *arrayValueC = [main objectForKey:#"valueC"];
NSDictionary *elem0 = [arrayValueC objectAtIndex:0];
NSString *stringC1 = [arrayValueC objectForKey:#"valueC1"];
NSLog(#"id: %#",arrayID);
NSLog(#"type: %#",arrayType);
NSLog(#"string: %#",stringC1);

Related

How do I interop with this Javascript code, from Fable F#?

I want to create a binding of the Plotly.js library to Fable.
I am looking at this js code
import React from 'react';
import Plot from 'react-plotly.js';
class App extends React.Component {
render() {
return (
<Plot
data={[
{
x: [1, 2, 3],
y: [2, 6, 3],
type: 'scatter',
mode: 'lines+points',
marker: {color: 'red'},
},
{type: 'bar', x: [1, 2, 3], y: [2, 5, 3]},
]}
layout={ {width: 320, height: 240, title: 'A Fancy Plot'} }
/>
);
}
}
and my (faulty) attempt of creating a simple test binding looks like this
open Fable.Core
open Fable.Core.JsInterop
open Browser.Types
open Fable.React
// module Props =
type Chart =
|X of int list
|Y of int List
|Type of string
type IProp =
| Data of obj list
let inline plot (props: IProp) : ReactElement =
ofImport "Plot" "react-plotly.js" props []
let myTrace = createObj [
"x" ==> [1,2,3]
"y" ==> [2,6,3]
"type" ==> "scatter"
"mode" ==> "lines"
]
let myData = Data [myTrace]
let testPlot = plot myData
But obviously it does not work. How do I get it to work? Also, what does {[...]} mean? I am new to Javascript, and as far as I know {...} denotes an object which must contain name value pairs, and [...] denotes an array. So {[...]} seems to denote an object with a single nameless member that is an array, but as far as I know, there are no objects with nameless members.
I have been able to reproduce the example you linked. Please note that I don't Plotly and that I went the empiric way and so things can probably be improved :)
I have created the code as I would probably have done it if I had to use it in my production app. So there is a bit more code than in your question because I don't use createObj.
If you don't like the typed DSL you can always simplify it, remove it and use createObj or anonymous record like I did for the marker property :)
You need to install both react-plotly.js plotly.js in your project.
open Fable.Core.JsInterop
open Fable.Core
open Fable.React
// Define props using DUs this helps create a typed version of the React props
// You can then transform a list of props into an object using `keyValueList`
[<RequireQualifiedAccess>]
type LayoutProps =
| Title of string
| Width of int
| Height of int
// GraphType is marked as a `StringEnum` this means
// the value will be replace at compile time with
// their string representation so:
// `Scatter` becomes `"scatter"`
// You can customise the output by using `[<CompiledName("MyCustomName")>]
[<RequireQualifiedAccess; StringEnum>]
type GraphType =
| Scatter
| Bar
[<RequireQualifiedAccess; StringEnum>]
type GraphMode =
| Lines
| Points
| Markers
| Text
| None
[<RequireQualifiedAccess>]
type DataProps =
| X of obj array
| Y of obj array
| Type of GraphType
| Marker of obj
// This is an helpers to generate the `flagList` waited by Plotly, if you don't like it you can just remove
// member and replace it with `| Mode of string` and so you have to pass the string by yourself
static member Mode (modes : GraphMode seq) : DataProps =
let flags =
modes
|> Seq.map unbox<string> // This is safe to do that because GraphMode is a StringEnum
|> String.concat "+"
unbox ("mode", flags)
[<RequireQualifiedAccess>]
type PlotProps =
| Nothing // Should have real props here is there exist more than Data and Layout
// Here notes that we are asking for an `Array` or Data
// Array being the type expected by the JavaScript library
// `DataProps seq` is our way to represents props
static member Data (dataList : (DataProps seq) array) : PlotProps =
let datas =
dataList
|> Array.map (fun v ->
keyValueList CaseRules.LowerFirst v // Transform the list of props into a JavaScript object
)
unbox ("data", datas)
static member Layout (props : LayoutProps seq) : PlotProps =
unbox ("layout", keyValueList CaseRules.LowerFirst props)
// All the example I saw from react-plotly was using this factory function to transform the plotly library into a React component
// Even, the example you shown if you look at the Babel tab in the live example
let createPlotlyComponent (plotly : obj) = import "default" "react-plotly.js/factory"
// Immport the plotly.js library
let plotlyLib : obj = import "default" "plotly.js"
// Apply the factory on the plotly library
let Plot : obj = createPlotlyComponent plotlyLib
// Helper function to instantiate the react components
// This is really low level, in general we use `ofImport` like you did but if I use `ofImport` then I got a React error
let inline renderPlot (plot : obj) (props : PlotProps list) =
ReactBindings.React.createElement(plot, (keyValueList CaseRules.LowerFirst props), [])
let root =
// Here we can render the plot using our Typed DSL
renderPlot
Plot
[
PlotProps.Data
[|
[
DataProps.X [| 1; 2; 3 |]
DataProps.Y [| 2; 6; 3 |]
DataProps.Type GraphType.Scatter
DataProps.Mode
[
GraphMode.Lines
GraphMode.Points
]
DataProps.Marker {| color = "red" |}
]
[
DataProps.Type GraphType.Bar
DataProps.X [| 1; 2; 3 |]
DataProps.Y [| 2; 5; 3 |]
]
|]
PlotProps.Layout
[
LayoutProps.Width 640
LayoutProps.Height 480
LayoutProps.Title "A Fancy Plot"
]
]
I'm a bit late to the party here, but wanted to give you a different option if you're still looking to use plotly.js with Fable.
I've been working on bindings for plotly.js for the past month or so, and it's in a pretty usable state as of now. That being said, I wouldn't say it's production ready.
This is what the example you want to convert would look like written with Feliz.Plotly:
open Feliz
open Feliz.Plotly
let chart () =
Plotly.plot [
plot.traces [
traces.scatter [
scatter.x [ 1; 2; 3 ]
scatter.y [ 2; 6; 3 ]
scatter.mode [
scatter.mode.lines
scatter.mode.markers
]
scatter.marker [
marker.color color.red
]
]
traces.bar [
bar.x [ 1; 2; 3 ]
bar.y [ 2; 5; 3 ]
]
]
plot.layout [
layout.width 320
layout.height 240
layout.title [
title.text "A Fancy Plot"
]
]
]
You can find more information out here.

how to get an array response of jdbc request in jmeter?

Example I have my JDBC Request and the response is like:
X Y Z
a1 b1 c1
a2 b2 c2
a3 b3 c3
a4 b4 c4
a5 b5 c5
. . .
. . .
. . .
How can I get all the value of x, y and z?
then I have HTTP request and I'm going to assert if all the response is matched to the data selected from JDBC.
example response:
{
{
"x":"a1",
"y":"b1",
"z": "c1"
},
{
"x":"a2",
"y":"b2",
"z": "c2"
},
{
"x":"a3",
"y":"b3",
"z": "c4"
},
{
"x":"a4",
"y":"b4",
"z": "c4"
},
{
"x":"a5",
"y":"b5",
"z": "c5"
},
{
"x":"a6",
"y":"b6",
"z": "c6"
},
{
"x":"a7",
"y":"b7",
"z": "c7"
},
{
"x":"a8",
"y":"b8",
"z": "c8"
},
.
.
.
.
}
As per JDBC Request sampler documentation:
If the Variable Names list is provided, then for each row returned by a Select statement, the variables are set up with the value of the corresponding column (if a variable name is provided), and the count of rows is also set up. For example, if the Select statement returns 2 rows of 3 columns, and the variable list is A,,C, then the following variables will be set up:
A_#=2 (number of rows)
A_1=column 1, row 1
A_2=column 1, row 2
C_#=2 (number of rows)
C_1=column 3, row 1
C_2=column 3, row 2
So given you provide "Variable Names" as X,Y,Z you should be able to access the values as ${X_1}, ${Y_2}, etc.
See Debugging JDBC Sampler Results in JMeter for more detailed information on working with JDBC Test Elements results and result sets.
You should declare the "Variable Names" field and also declare a result variable name as shown below.
Then you can access them using the _1 _2 method. Please find below the sample code that you can use in the beanshell post processor.
import java.util.ArrayList;
import net.minidev.json.parser.JSONParser;
import net.minidev.json.JSONObject;
import net.minidev.json.JSONArray;
ArrayList items = vars.getObject("result1");
for ( int i = items.size() - 1; i >= 0; i--) {
JSONObject jsonitemElement = new JSONObject();
jsonitemElement.put("x", vars.get("x_" + (i + 1)));
jsonitemElement.put("y", vars.get("y_" + (i + 1)));
jsonitemElement.put("z", vars.get("z_" + (i + 1)));
log.info(jsonitemElement.toString());
}
Since you are getting these values as the response from the response payload of the HTTP request, you should add the code to parse that JSON response in an assertion or post processor and compare it with the elements from the above sample code.
A point to note - Different applications send the target JSON in any order. So, there is no guarantee that the HTTP response will always send the response as A1,B1,C1 - A2,B2,C2 etc. It can send them in any order starting with A5,B5,C5 etc. It is better to then use a hashmap or write your array comparison to ensure that your result set completely matches the HTTp response.

Elm - Random Number on init strange behaviour

Just working through the samples, and got the exercise about creating 2 random dice and rolling them with a button.
http://guide.elm-lang.org/architecture/effects/random.html
So I thought I would create the dice as a module, remove the roll action, and just have it create a D6 value on init.
So my code is now as follows (should open direct in elm-reactor)
module Components.DiceRoller exposing (Model, Msg, init, update, view)
import Html exposing (..)
import Html.App as Html
import Html.Attributes exposing (..)
import Html.Events exposing (..)
import Random
import String exposing (..)
main =
Html.program
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}
-- MODEL
type alias Model =
{ dieFace : Int
}
init : ( Model, Cmd Msg )
init =
( Model 0, (Random.generate NewFace (Random.int 1 6)) )
-- UPDATE
type Msg
= NewFace Int
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
NewFace newFace ->
( Model newFace, Cmd.none )
-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions model =
Sub.none
-- VIEW
dieFaceImage : Int -> String
dieFaceImage dieFace =
concat [ "/src/img/40px-Dice-", (toString dieFace), ".svg.png" ]
view : Model -> Html Msg
view model =
let
imagePath =
dieFaceImage model.dieFace
in
div []
[ img [ src imagePath ] []
, span [] [ text imagePath ]
]
The problem with this is that it is always producing the same value. I thought I had a problem with the seed to begin with, but if you change
init =
( Model 0, (Random.generate NewFace (Random.int 1 6)) )
init =
( Model 0, (Random.generate NewFace (Random.int 1 100)) )
it works exactly as intended. So it looks like the default generator is not working with small values, seems to work as low down as 10.
The odd thing is this, in this example (which i started with) http://guide.elm-lang.org/architecture/effects/random.html , it works fine with 1-6 when it's not in init.
So my question is, am I doing something wrong, or is this just a wrinkle in elm? Is my usage of the command in init ok?
In the end, I put this in to get the desired effect, which feels wonky.
init =
( Model 0, (Random.generate NewFace (Random.int 10 70)) )
with
NewFace newFace ->
( Model (newFace // 10), Cmd.none )
This must to have something to do with seeding. You're not specifying any value for seed so the generator is defaulting to use the current time.
I think you tried to refresh your page for a few times in a few seconds and you didn't see the value change. If you wait for longer (roughly a minute) you'll see your value change.
I had a look at the source code of Random and I suspect that for seed values that are close enough the first value generated in the range [1,6] doesn't change. I'm not sure whether this is expected or not, probably it's worth raising an issue on GitHub

Count number of dictionarys in dictionary in swift

I have a buch of accounts stored in a string dictionary and i would like to count the number of accounts existing, so basicly a ".count" but to find the number of dictionaries created.
var dictionary: [String : [ String ]] = ["" : []]
let storeString = "StoreString"
func addUpdateArray(strings: [String], index: Int) {
let locator = storeString + index.description
dictionary[locator] = strings
}
addUpdateArray(["Account1", "Hy"], 1)
addUpdateArray(["Account2", "Hey"], 3)
and now I would like to see how many accounts are have created of the kind dictionary, is ther a way?
Something like this?
var accounts = [String:[String:String]]() // or whatever your structure is
accounts["Edmund"] = [
"amount": "23.87",
"curreny": "dollars"
]
accounts["Baldrick"] = [
"amount": "23.87",
"curreny": "dollars"
]
accounts["Percy"] = [
"amount": "87.00",
"curreny": "peso"
]
println(accounts.keys.array.count) // 3
If you have dictionary of dictionaries and you want to count the number of actual values inside, you can do it like this:
var accounts = [
"accountsGroup1" : ["account1", "account2", "account3", "account4"],
"accountsGroup2" : ["account1", "account2"],
"accountsGroup3" : ["account1", "account2", "account3", "account4"]
]
let accountsCount = accounts.values.map { $0.count }
let numberOfAllAccounts = reduce(accountsCount, 0) { $0 + $1 }
println(numberOfAllAccounts)

Initializing NSOpenGLPixelFormat in Swift

Apparently I'm the only one to attempt this, as none of my Google searches turned up anything helpful. Assume I'm initializing an attribute array like this:
let glPFAttributes = [
NSOpenGLPFAAccelerated,
NSOpenGLPFADoubleBuffer,
NSOpenGLPFAColorSize, 48,
NSOpenGLPFAAlphaSize, 16,
NSOpenGLPFAMultisample,
NSOpenGLPFASampleBuffers, 1,
NSOpenGLPFASamples, 4,
NSOpenGLPFAMinimumPolicy,
0
]
These things are all regular Ints, I've checked. Now if I do
let glPixelFormat = NSOpenGLPixelFormat(attributes: glPFAttributes)
the compiler gives me this error message:
'Int' is not identical to 'NSOpenGLPixelFormatAttribute'
If I made a mistake somewhere, I'm not seeing it.
NSOpenGLPixelFormatAttribute is typeAlias of UInt32. NSOpenGLPixelFormat intializer takes array of NSOpenGLPixelFormatAttribute so you need to make array and convert all Int to UInt32.Below code will work
let glPFAttributes:[NSOpenGLPixelFormatAttribute] = [
UInt32(NSOpenGLPFAAccelerated),
UInt32(NSOpenGLPFADoubleBuffer),
UInt32(NSOpenGLPFAColorSize), UInt32(48),
UInt32(NSOpenGLPFAAlphaSize), UInt32(16),
UInt32(NSOpenGLPFAMultisample),
UInt32(NSOpenGLPFASampleBuffers), UInt32(1),
UInt32(NSOpenGLPFASamples), UInt32(4),
UInt32(NSOpenGLPFAMinimumPolicy),
UInt32(0)
]
let glPixelFormat = NSOpenGLPixelFormat(attributes: glPFAttributes)

Resources