Assign array to JSON object as a new object - json

I have an array which includes some values, ex.
let array = [value1, value2];
How can I create a JSON object like the following?
{
"field": "[value1, value2]"
}

Use JSON.stringify() method:
let array = [value1, value2];
let yourJObject={"field":JSON.stringify(array)}

JSON.stringify for output a json, ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
I think you could find it pretty easily with a Google search :)
const result = JSON.stringify({ field: ["toto", "tutu"]})
console.log(result)

Related

Parse json in node js

Can someone help me with this json {"event":"update","data":"{\"asks\":[[\"55.5\",\"5.3744\"],[\"55.74\",\"0.8087\"]]}}, how parse this values from json 55.5 and 5.3744. I will be grateful for help.
Your JSON is invalid and cannot be parsed.
I assume your data is a JSON string within a JSON string that should be parsed after the main JSON string has been parsed. This is not really efficient and you should consider not stringifying the data value in the first place.
Your JSON should look like this:
{"event":"update","data":{"asks":[["55.5","5.3744"],["55.74","0.8087"]]}}
Or:
{\"event\":\"update\",\"data\":{\"asks\":[[\"55.5\",\"5.3744\"],[\"55.74\",\"0.8087\"]]}}
In JavaScript:
const json = '{"event":"update","data":{"asks":[["55.5","5.3744"],["55.74","0.8087"]]}}';
const obj = JSON.parse(json);
const val1 = obj.data.asks[0][0];
const val2 = obj.data.asks[0][1];
If you must have data as a JSON encoded string, encode it correctly. If you want to know what your JSON string should look like in this case, work backwards:
const dataString = JSON.stringify({
asks: [
["55.5", "5.3744"],
["55.74","0.8087"]
]
});
const jsonString = JSON.stringify({
event: "update",
data: dataString
});
// {\"event\":\"update\",\"data\":\"{\\\"asks\\\":[[\\\"55.5\\\",\\\"5.3744\\\"],[\\\"55.74\\\",\\\"0.8087\\\"]]}\"}
// And back again...
const asks = JSON.parse(
JSON.parse(jsonString).data
).asks;
const val1 = asks[0][0];
const val2 = asks[0][1];

Convert JSON output to an array with SwiftyJSON

I have this subJSON["guestpics"] as JSON data from SwiftyJSON.
When I print(subJSON["guestpics"]) I have this:
[
"/images\/profile_pic\/1.jpg",
"/images\/profile_pic\/2.jpg",
"/images\/profile_pic\/3.jpg"
]
How can I convert this to an array ?
for (_, subJSON): (String, JSON) in json[0]["data"] {
print(subJSON["guestpics"])
}
SwiftyJSON has already parsed your JSON data and prepared typed objects.
If the key subJSON["guestpics"] contains an array, then use SwiftyJSON's optional getter .array to get it:
if let guestPicsArray = subJSON["guestpics"].array {
// here "guestPicsArray" is your array
}
Why not directly storing the value of the key in the array? as it look like array
Does it show any error/crash when you are trying to store ?
if let arrGuest = subJSON["guestpics"] as? Array<String> {
}
Or if you are more familiar with Objective-c
if let arrGuest = arr as? NSArray {
}
you can get the array in the arrGuest object

How would I parse this type of JSON using SwiftyJSON?

[
{
"ID": 0,
"Name": "PHI"
},
{
"ID": 0,
"Name": "ATL"
}
]
I'm using SwiftyJSON and Alamofire. This is what is being returned. I want to loop through each of these objects now in my code. I'm having trouble getting this information though.
json[0]["Name"].string seems to return nil, and I'm not sure why. The JSON object is definitely getting the JSON, when I print it to the console it looks exactly like above.
I also tried:
var name = json[0].dictionary?["Name"]
Still nil though.
Any ideas?
EDIT
Here's the code I'm using to retrieve the JSON.
Alamofire.request(.GET, "url", parameters: nil, encoding: .JSON, headers: nil).responseJSON
{
(request, response, data, error) in
var json = JSON(data!)
//var name = json[0].dictionary?["Name"]
}
Your JSON is valid (at least this snippet is), and your first method to retrieve the data from SwiftyJSON is correct.
On the other hand, the Alamofire snippet you showed didn't compile for me, I had to change the signature.
Given that in the comments you say that not only json[0]["Name"] is nil but json[0] is also nil, I think you have a problem with how your data is fetched.
I tested this version of the Alamofire method in a sample app and it worked well:
Alamofire.request(.GET, yourURL).responseJSON(options: nil) { (request, response, data, error) in
let json = JSON(data!)
let name = json[0]["Name"].string
println(name)
}
In the screenshot, the URL is my local server, with your JSON copy pasted in "test.json".
This "answer" is an extension of my comment, I needed room to show more info...
I think you might try this.
first convert JSON(data) using swifyJSON
let json = JSON(data!)
then count the array element in data.
let count: Int? = json.array?.count
after that use for loop to reach array element one.
for index in 0...count-1 {
self.idArray.append(json[index]["ID"].stringValue)
self.nameArray.append(json[index]["Name"].stringValue)
}
you will get sorted data in "idArray" and "nameArray". try to print both the array.
You do not have to use index to parse array. You can get single json object from array and use it to access the data:
for (index: String, subJson: JSON) in json {
println("Current Index = \(index)")
if let _id = subJson["ID"].int {
println("ID = \(_id)")
} else {
println("Error ID")
}
if let _name = subJson["Name"].string {
println("Name = \(_name)")
} else {
println("Error Name")
}
}

Swift JSON add new key to existing dictionary

I'm using Alamofire and SwiftyJSON to get and manage data from an API
After making my initial request I end up with nested collection of type JSON
According to SwiftyJSON I can loop through data like so
https://github.com/SwiftyJSON/SwiftyJSON#loop
for (key: String, subJson: JSON) in json {
//Do something you want
}
Again, according to SwiftyJSON I should be able to set new values like so:
https://github.com/SwiftyJSON/SwiftyJSON#setter
json["name"] = JSON("new-name")
I have a nested collection of data and I can dig in as deep as I want, but I'm unable to alter the object and set new key:value pair. How would I got about doing this in Swift?
Here's my code :
for (key: String, stop: JSON) in stops {
var physicalStops = stop["physicalStops"]
for (key: String, physicalStop: JSON) in physicalStops {
println("Prints out \(physicalStop) just fine")
// physicalStop["myNewkey"] = "Somevalue" // DOES NOT WORK (#lvalue is not identical to 'JSON)
// physicalStop["myNewkey"] = JSON("Somevalue") //SAME Story
}
}
Basically I'd like to keep the very same structure of the original JSON object, but add additional key:value on the second level nesting for each sub object.
First, you can use var in for-loop to make value modifiable inside the loop. However, JSON is struct so it behaves as a value type, so in your nested example, you have to reassign also the child JSON to the parent JSON otherwise it just modifies the value inside the loop but not in the original structure
var json: JSON = ["foo": ["amount": 2], "bar": ["amount": 3]]
for (key: String, var item: JSON) in json {
println("\(key) -> \(item)")
item["price"] = 10
json[key] = item
}
println(json)
Below is code that runs fine in Swift 2 playground and does not require Swifty:
var json: [String:AnyObject] = ["foo": ["amount": 2], "bar": ["amount": 3]]
for (key,item) in json {
print("\(key) -> \(item)")
let newItem = ["price": 10]
json[key] = newItem
}
print(json)

How to deserialize JSON to a Swift object?

Is there any way to deserialize JSON to a Swift object, not to NSDictionay?
For example: a JSON is like: {"value": "xxx"}
I want to use this resource like:
var json = "{\"value\": \"xxx\"}"
var obj = parseToObj(json)
println(obj.value)
I wrote a small library to handle things like this swiftly. (No pun intended) You can get it here: JSONHelper
After reading your question I realized that I should add deserialization support directly from JSON strings and not just JSON response objects, so I did.
Here is how you do it:
struct MyObjectType: Deserializable {
var value: String?
init(data: [String: AnyObject]) {
value <-- data["value"]
}
}
var json = "{\"value\": \"xxx\"}"
var myClass: MyClass?
myClass <-- json
println("\(myClass.value)")