无法使用java解析嵌套json文件的键和值

时间:2017-06-22 07:31:03

标签: java json

下面是我要解析的json文件。我想打印所有键和相应的值。

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Iterator;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.simple.parser.JSONParser;

public class FetchJsonNested {
    public static void main(String args[]) throws FileNotFoundException {
        try {
            JSONParser jp=new JSONParser();
            Object obj=jp.parse(new FileReader("C:\\Users\\DELL\\Documents\\NetBeansProjects\\WaterNetwork\\web\\kusharray.json"));
            JSONObject job=(JSONObject)obj;
            Iterator < ? > keys = job.keys();

            while (keys.hasNext()) {
                String key = (String) keys.next();
                System.out.println(key);
                if (job.get(key) instanceof JSONObject) {
                    System.out.println(job.get(key));
                }
            }
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}

我尝试过以下代码:

Traceback (most recent call last):
  File "C:/Users/yyb/PycharmProjects/untitled1/myLSTM.py", line 49, in <module>
    regressor.fit(train_X,train_y,batch_size=BATCH_SIZE,steps=TRAINING_STEPS)
  File "C:\Users\yyb\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\util\deprecation.py", line 289, in new_func
    return func(*args, **kwargs)
  File "C:\Users\yyb\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\contrib\learn\python\learn\estimators\estimator.py", line 439, in fit
    SKCompat(self).fit(x, y, batch_size, steps, max_steps, monitors)
  File "C:\Users\yyb\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\contrib\learn\python\learn\estimators\estimator.py", line 1350, in fit
    monitors=all_monitors)
  File "C:\Users\yyb\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\util\deprecation.py", line 289, in new_func
    return func(*args, **kwargs)
  File "C:\Users\yyb\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\contrib\learn\python\learn\estimators\estimator.py", line 455, in fit
    loss = self._train_model(input_fn=input_fn, hooks=hooks)
  File "C:\Users\yyb\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\contrib\learn\python\learn\estimators\estimator.py", line 955, in _train_model
    model_fn_ops = self._get_train_ops(features, labels)
  File "C:\Users\yyb\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\contrib\learn\python\learn\estimators\estimator.py", line 1162, in _get_train_ops
    return self._call_model_fn(features, labels, model_fn_lib.ModeKeys.TRAIN)
  File "C:\Users\yyb\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\contrib\learn\python\learn\estimators\estimator.py", line 1133, in _call_model_fn
    model_fn_results = self._model_fn(features, labels, **kwargs)
  File "C:/Users/yyb/PycharmProjects/untitled1/myLSTM.py", line 35, in lstm_model
    output,_=tf.nn.dynamic_rnn(cell,x_,dtype=tf.float32)
  File "C:\Users\yyb\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\ops\rnn.py", line 574, in dynamic_rnn
    dtype=dtype)
  File "C:\Users\yyb\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\ops\rnn.py", line 637, in _dynamic_rnn_loop
    for input_ in flat_input)
  File "C:\Users\yyb\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\ops\rnn.py", line 637, in <genexpr>
    for input_ in flat_input)
  File "C:\Users\yyb\AppData\Local\Programs\Python\Python36\lib\site-packages\tensorflow\python\framework\tensor_shape.py", line 649, in with_rank_at_least
    raise ValueError("Shape %s must have rank at least %d" % (self, rank))
ValueError: Shape (10, ?) must have rank at least 3


#coding=utf-8
import numpy as np
import tensorflow as tf
import matplotlib as mpl
mpl.use('Agg')
from matplotlib import pyplot as plt



learn=tf.contrib.learn

HIDDEN_SIZE=30    
NUM_LAYERS=2    
TIMESTEPS=10    
TRAINING_STEPS=10000    
BATCH_SIZE=32       
TRAINING_EXAMPLES=10000      
TESTING_EXAMPLES=1000    
SAMPLE_GAP=0.01      

def generate_data(seq):
    X=[]
    y=[]
    for i in range(len(seq)-TIMESTEPS-1):
        X.append([seq[i:i+TIMESTEPS]])
        y.append([seq[i+TIMESTEPS]])
    return np.array(X,dtype=np.float32),np.array(y,dtype=np.float32)

def lstm_model(X,y):
    lstm_cell=tf.nn.rnn_cell.BasicLSTMCell(HIDDEN_SIZE)
    cell=tf.nn.rnn_cell.MultiRNNCell([lstm_cell]*NUM_LAYERS)

    x_=tf.unstack(X,axis=1)

    output,_=tf.nn.dynamic_rnn(cell,x_,dtype=tf.float32)

    output=output[-1]
    prediction,loss=learn.models.linear_regression(output,y)
    train_op=tf.contrib.layers.optimize_loss(loss,tf.contrib.framework.get_global_step(),optimizer="Adagrad",learning_rate=0.1)
    return prediction,loss,train_op

regressor=learn.Estimator(model_fn=lstm_model)

test_start=TRAINING_EXAMPLES*SAMPLE_GAP
test_end=(TRAINING_EXAMPLES+TESTING_EXAMPLES)*SAMPLE_GAP
train_X,train_y=generate_data(np.sin(np.linspace(0,test_start,TRAINING_EXAMPLES,dtype=np.float32)))
test_X,test_y=generate_data(np.sin(np.linspace(test_start,test_end,TESTING_EXAMPLES,dtype=np.float32)))

regressor.fit(train_X,train_y,batch_size=BATCH_SIZE,steps=TRAINING_STEPS)

predicted=[[pred] for pred in regressor.predict(test_X)]

rmse=np.sqrt(((predicted-test_y)**2).mean(axis=0))
print('Mean square error is: %f'%rmse[0])

fig=plt.figure()
plot_predicted=plt.plot(predicted,label='predicted')
plot_test=plt.plot(test_y,label='real_sin')
plt.legend([plot_predicted,plot_test],['predicted','real_sin'])
fig.savefig('sin.png')

我已经阅读了许多网站的内容,但没有人像我想要的那样工作。我想打印所有密钥和相应的值。

2 个答案:

答案 0 :(得分:1)

像在示例中一样使用org.json:

String jsonStr = "{\"A\":{\"name\":\"Ram\",\"gender\":\"male\",\"designation\":\"engineer\"},\"B\":{\"name\":\"Shyam\",\"gender\":\"male\",\"designation\":\"student\"},\"C\":{\"name\":\"Mohan\",\"gender\":\"male\",\"designation\":\"manager\"}}";
JSONObject json = new JSONObject(jsonStr);

for (Object key : json.keySet().toArray()){
    JSONObject data = json.getJSONObject(key.toString());
    System.out.println("json :" + data.toString());
    System.out.println("name :" +data.getString("name"));
    System.out.println("gender :" +data.getString("gender"));
    System.out.println("designation :" +data.getString("designation"));
}

现在你可以替换我的第一行&#34; String jsonStr = ...&#34;用你的文件阅读器。

答案 1 :(得分:0)

下面没有关注那个令人敬畏和最优雅的解决方案,但这可以引导您达到您的需求。

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;

public class Main {

    public static void main(String[] args) throws Exception {
        String jsonString = loadJSONFile();

        JsonElement jsonElement = new JsonParser().parse(jsonString);
        JsonObject jsonObject = jsonElement.getAsJsonObject();

        print(jsonObject);
    }

    private static String loadJSONFile() throws FileNotFoundException {
        Scanner scanner = new Scanner(new FileReader("path/to/the/json/file.ext"));
        StringBuilder stringBuilder = new StringBuilder();

        while (scanner.hasNext()) {
            stringBuilder.append(scanner.next());
        }

        scanner.close();

        return stringBuilder.toString();
    }

    private static void print(JsonObject jsonObject) {
        Set<Map.Entry<String, JsonElement>> entries = jsonObject.entrySet();

        for (Map.Entry<String, JsonElement> entry : entries) {
            System.out.println(entry.getKey() + ": " + entry.getValue());

            try {
                JsonElement jsonElement = new JsonParser().parse(String.valueOf(entry.getValue()));
                JsonObject innerJsonObject = jsonElement.getAsJsonObject();

                print(innerJsonObject);
            } catch (Exception e) {
                // is not a JSON
            }
        }
    }
}

输出示例:

A: {"name":"Ram","gender":"male","designation":"engineer"}
name: "Ram"
gender: "male"
designation: "engineer"
B: {"name":"Shyam","gender":"male","designation":"student"}
name: "Shyam"
gender: "male"
designation: "student"
C: {"name":"Mohan","gender":"male","designation":"manager"}
name: "Mohan"
gender: "male"
designation: "manager"